We use cookies for analytics and advertising. Ads are disabled until you accept advertising cookies. Read our Cookie Policy and Privacy Policy.
Next.js Authentication Across Multiple Subdomains Guide | TVerge Tech
Next.js Authentication Across Multiple Subdomains Guide
Learn Next.js authentication across multiple subdomains: share cookies safely, set Domain correctly, handle CORS, CSRF and logout, and test it end to end.
Next.js Authentication Across Multiple Subdomains: A Complete Guide
Most products outgrow a single hostname. A marketing site lives at www.example.com, the product at app.example.com, an admin console at admin.example.com, and an API at api.example.com. Users expect to sign in once and move between them without seeing another login screen.
On paper, the fix looks like one cookie attribute. In practice, Next.js authentication across multiple subdomains touches cookie scoping, CORS, CSRF, local development, deployment and the security of every hostname under your domain. A setup that works on your laptop can fail silently in production, or work in a way that quietly widens your attack surface.
This guide covers how browsers scope cookies, three architectures you can choose from, a working shared-session implementation with the Next.js App Router, an Auth.js configuration, credentialed API calls between subdomains, local and Vercel setup, multi-tenant considerations, and a security checklist.
"Sign in once, use everywhere" depends on three separate questions:
Where does the session live? Usually in a cookie, either holding a signed token or an opaque session ID that points to a record on your server.
Who is allowed to read it? Only the host that created it, or every subdomain under your parent domain.
Who verifies it? Each app independently, or one central service.
Two terms are easy to confuse:
Term
Example
Comparison rule
Origin
https://app.example.com
Scheme, host and port must all match
Site
example.com (registrable domain)
Scheme and registrable domain must match
app.example.com and api.example.com are different origins but the same site. That distinction drives most of the behavior in this guide:
Cross-origin rules such as CORS and the Origin header apply between them.
Same-site rules such as SameSite cookies treat them as the same party.
Your authentication design has to respect both.
How browsers decide which cookies a subdomain receives
Host-only cookies versus domain cookies
A cookie set without a Domain attribute is host-only. The browser sends it only to the exact host that set it. If auth.example.com sets a session cookie with no Domain, app.example.com never sees it.
A cookie set with Domain=example.com is sent to example.com and all of its subdomains. This is the mechanism behind shared sessions. The IETF cookie specification, RFC 6265, defines the behavior, and the MDN guide to Set-Cookie summarizes it for developers.
The leading dot is not required
Older articles tell you to write .example.com. Per RFC 6265, a leading dot is ignored, so Domain=example.com and Domain=.example.com behave the same in modern browsers. Either works. Many guides still show the dot for historical reasons.
You cannot set cookies on public suffixes
Browsers refuse cookies scoped to public suffixes such as com, co.uk or vercel.app, based on the Public Suffix List. Two consequences follow:
Two projects on project-a.vercel.app and project-b.vercel.app are different sites and can never share a cookie.
Shared sessions require a domain you own, such as example.com.
Cookie prefixes
Prefixes make browsers enforce extra rules on a cookie:
Prefix
Requirements
Works for shared sessions?
__Secure-
Must have Secure, set over HTTPS
Yes
__Host-
Secure, Path=/, and noDomain attribute
No, it forces host-only
__Host- is the stronger prefix because it blocks sibling subdomains from overwriting the cookie, but it cannot be shared. Use __Host- for host-only sessions (Pattern 2) and __Secure- for shared sessions (Pattern 1).
Size limits
Browsers typically cap a single cookie at about 4 KB. A domain cookie is also attached to every request to every subdomain, including images and scripts if they are served from a subdomain. Keep the payload small and avoid serving static assets from subdomains that receive the session cookie.
Choosing an architecture
There are three common patterns. Pick based on how much you trust all your subdomains and whether you need to isolate them.
Pattern
How it works
Strengths
Trade-offs
1. Shared session cookie
One cookie with Domain=example.com; every app verifies it with a shared secret or shared session store
Simple, no redirects between apps
Any subdomain can read it, and a compromised one exposes every user
2. Central auth host + SSO
auth.example.com signs users in, then hands each app a one-time code to exchange for its own host-only session
Better isolation, works across different registrable domains
More moving parts and redirects
3. Hybrid
Pattern 2 for sign-in, Pattern 1 only among a small trusted set of apps
Balances UX and isolation
Needs clear boundaries to avoid confusion
A reasonable rule of thumb:
Use Pattern 1 when every subdomain is your own code, deployed by the same team, with the same security posture.
Use Pattern 2 when some subdomains run third-party code, user-generated content, customer-specific apps or lower-trust tooling, or when you need to span multiple registrable domains.
Pattern 1: a shared session cookie
This walkthrough assumes the App Router and a monorepo with a shared auth package:
Sign-in happens at one place, for example auth.example.com or app.example.com. Every other app only reads and verifies the cookie.
Step 1: Shared environment variables
Every app needs the same values:
# Same value in every app that verifies the session
SESSION_SECRET="generate-a-long-random-value"
AUTH_COOKIE_DOMAIN="example.com"
AUTH_URL="https://auth.example.com"
Generate the secret with a cryptographically secure source, for example openssl rand -base64 32, and store it in your hosting provider's secret manager. Never commit it. For HS256 signing, use at least 32 bytes of randomness.
In local development, leave AUTH_COOKIE_DOMAIN unset or use a dev domain (see the local development section).
Step 2: Cookie configuration
Keep cookie options in one place so every app sets and clears the cookie identically:
httpOnly keeps the cookie out of reach of client-side JavaScript, which limits the damage of an XSS bug.
secure restricts the cookie to HTTPS. The __Secure- name makes browsers enforce it.
sameSite: "lax" is a sensible default for sign-in flows that include top-level redirects. Later sections explain why it is not enough on its own across subdomains.
domain is the line that enables sharing. If it is undefined, the cookie is host-only.
Step 3: Sign and verify the token
The Next.js authentication guide recommends using a session library such as Jose for stateless sessions. This example uses it:
A signed JWT is not encrypted. Anyone who holds the cookie can read the payload, so keep it minimal. A session ID and a user ID are enough, and nothing sensitive belongs inside.
Always pass algorithms, issuer and audience to jwtVerify so a token minted for another purpose is rejected.
If you want to inspect a token while debugging, the Base64 Encoder & Decoder can show the readable payload segment, and the JSON Formatter & Validator makes it easier to read. Decoding is not verification, and only your server can confirm the signature.
Step 4: Create and delete the session
Cookies can only be set in Server Functions (Server Actions) or Route Handlers, not while rendering a Server Component. See the cookies API reference.
// packages/auth/src/actions.ts
import "server-only";
import { cookies } from "next/headers";
import { SESSION_COOKIE, sessionCookieOptions } from "./cookie";
import { signToken } from "./session";
export async function createSession(userId: string) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const token = await signToken({ sid: crypto.randomUUID(), userId }, expiresAt);
const jar = await cookies();
jar.set(SESSION_COOKIE, token, sessionCookieOptions(expiresAt));
}
export async function deleteSession() {
const jar = await cookies();
// Same name, path and domain as the original cookie, otherwise the
// browser treats it as a different cookie and keeps the old one.
jar.set(SESSION_COOKIE, "", {
...sessionCookieOptions(new Date(0)),
maxAge: 0,
});
}
The logout detail is a common source of "I logged out but I'm still signed in on another subdomain" bugs. A cookie is identified by its name, domain and path. If you clear it with different attributes than you set it with, the original survives.
Step 5: A single place to verify sessions
Centralize verification in a small data access layer so pages, Server Actions and Route Handlers all use the same check. Wrapping it in React's cache avoids repeating the work within a request:
// packages/auth/src/dal.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { SESSION_COOKIE } from "./cookie";
import { verifyToken } from "./session";
export const getSession = cache(async () => {
const jar = await cookies();
return verifyToken(jar.get(SESSION_COOKIE)?.value);
});
export async function requireSession(returnTo: string) {
const session = await getSession();
if (!session) {
const url = new URL("/login", process.env.AUTH_URL);
url.searchParams.set("returnTo", returnTo);
redirect(url.toString());
}
return session;
}
If you model the result of getSession as a union such as { status: "authenticated" } | { status: "anonymous" }, our guide to TypeScript discriminated unions shows how to narrow it safely.
Step 6: Use the proxy for fast, optimistic checks
Next.js 16 renamed the middleware file convention to proxy. On older versions, use middleware.ts with the same logic. The proxy.js reference covers the details.
// apps/app/proxy.ts
import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE } from "@acme/auth/cookie";
import { verifyToken } from "@acme/auth/session";
export async function proxy(request: NextRequest) {
const token = request.cookies.get(SESSION_COOKIE)?.value;
const session = await verifyToken(token);
if (!session) {
const login = new URL("/login", process.env.AUTH_URL);
login.searchParams.set("returnTo", request.nextUrl.href);
return NextResponse.redirect(login);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|login).*)"],
};
Use a negative matcher so authentication redirects do not block CSS, JavaScript or images. Treat the proxy as a first line of defense, not the only one. The Next.js Data Security guide recommends verifying authorization close to the data, so call requireSession in your Server Components, Server Actions and Route Handlers too.
Step 7: Validate the redirect target
The returnTo parameter is an open redirect risk if you trust it blindly. An attacker could craft a login link that sends users to a malicious site after they authenticate. Allow only hosts you control:
// packages/auth/src/redirect.ts
const ALLOWED_HOSTS = new Set([
"www.example.com",
"app.example.com",
"admin.example.com",
]);
export function safeReturnTo(raw: string | null, fallback: string) {
if (!raw) return fallback;
try {
const url = new URL(raw);
if (url.protocol === "https:" && ALLOWED_HOSTS.has(url.hostname)) {
return url.toString();
}
} catch {
// Malformed URL, fall through to the fallback.
}
return fallback;
}
Then use it after a successful sign-in:
"use server";
import { redirect } from "next/navigation";
import { createSession } from "@acme/auth/actions";
import { safeReturnTo } from "@acme/auth/redirect";
export async function login(formData: FormData) {
const email = String(formData.get("email") ?? "");
const password = String(formData.get("password") ?? "");
const returnTo = String(formData.get("returnTo") ?? "") || null;
const user = await verifyCredentials(email, password); // your own logic
if (!user) return { error: "Invalid email or password." };
await createSession(user.id);
redirect(safeReturnTo(returnTo, "https://app.example.com"));
}
Pattern 2: a central auth host with single sign-on
When you want isolation between subdomains, keep the long-lived credential on one host and give each app its own session.
The flow looks like this:
A user visits app.example.com with no session.
The app redirects them to auth.example.com/login?returnTo=....
The user signs in. auth.example.com keeps a host-only session cookie (a good fit for the __Host- prefix).
auth.example.com redirects back to the app with a short-lived, single-use authorization code.
The app's server exchanges that code for the user's identity and sets its own host-only session cookie.
When the user visits admin.example.com, the same redirect happens, but step 3 already has a session, so the user is bounced straight back without typing anything.
Design rules that keep this safe:
The code must be single-use, expire within a minute or so, and be bound to the destination app.
Exchange the code on the server, never in client-side JavaScript.
Validate returnTo exactly as in Pattern 1.
Prefer a standard such as OpenID Connect over a hand-rolled protocol when you can. Many identity providers support it.
The trade-off is extra redirects and more code to maintain. The benefit is that a compromised subdomain exposes only its own session. It does not expose a credential every other subdomain accepts. This pattern also keeps working if you later add a second registrable domain.
Configuring Auth.js for subdomains
If you use Auth.js, you can scope the session cookie through the cookies option. Cookie names differ between versions (authjs.session-token in v5, next-auth.session-token in v4), so confirm the names in your own browser's developer tools and in the Auth.js documentation.
Every app that reads the session must use the same AUTH_SECRET and the same cookie name. Auth.js derives its token encryption from both, so a mismatch shows up as a decryption error.
OAuth sign-in uses short-lived helper cookies such as state and the PKCE verifier. Run the sign-in flow on one host and register a single callback URL with your provider, rather than starting OAuth from several subdomains.
Do not share a cookie between apps that use different Auth.js configurations or callbacks that add different claims to the token.
Calling APIs across subdomains with CORS
Sharing a cookie does not remove the browser's cross-origin rules. If app.example.com calls api.example.com with fetch, both sides must opt in to credentials.
On the client:
const res = await fetch("https://api.example.com/me", {
credentials: "include",
});
On the API (a Next.js Route Handler):
// apps/api/app/me/route.ts
import { NextResponse } from "next/server";
import { getSession } from "@acme/auth/dal";
const ALLOWED_ORIGINS = new Set([
"https://app.example.com",
"https://admin.example.com",
]);
function corsHeaders(origin: string | null) {
const headers = new Headers({ Vary: "Origin" });
if (origin && ALLOWED_ORIGINS.has(origin)) {
headers.set("Access-Control-Allow-Origin", origin);
headers.set("Access-Control-Allow-Credentials", "true");
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
headers.set("Access-Control-Allow-Headers", "Content-Type");
}
return headers;
}
export async function OPTIONS(request: Request) {
return new NextResponse(null, {
status: 204,
headers: corsHeaders(request.headers.get("origin")),
});
}
export async function GET(request: Request) {
const headers = corsHeaders(request.headers.get("origin"));
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401, headers });
}
return NextResponse.json({ userId: session.userId }, { headers });
}
The rules that trip people up:
When credentials are included, Access-Control-Allow-Origincannot be *. Echo back a specific allowed origin.
Compare the incoming Origin against an allowlist. Never reflect it blindly.
Add Vary: Origin so caches do not serve one origin's headers to another.
Your API must still verify the session. CORS controls what browsers expose to scripts. It does not authenticate anyone.
Local development with real hostnames
Domain cookies are hard to test on plain localhost, because browsers handle Domain=localhost inconsistently. A more reliable approach is to use real-looking hostnames:
Pick a development domain under a reserved suffix such as example.test.
Whatever host you deploy on, a few points are universal:
Add every subdomain as a custom domain on the project that serves it. The Vercel domains documentation explains adding and verifying domains, including wildcard requirements.
Set the sameSESSION_SECRET, AUTH_COOKIE_DOMAIN and AUTH_URL in every project that verifies the session. A mismatched secret in just one app is a frequent cause of "works on app, fails on admin."
Preview deployments on *.vercel.app cannot share cookies with each other or with your production domain, because vercel.app is a public suffix. If you need to test cross-subdomain sessions before release, assign preview URLs under your own domain, or test on a staging domain.
Rotate secrets deliberately. Changing SESSION_SECRET invalidates every existing session, which may be what you want after an incident and a disruption otherwise.
Multi-tenant apps: authentication is not authorization
SaaS products often give each customer a subdomain, such as acme.example.com and globex.example.com. A shared parent-domain cookie means a user signed in to one tenant sends the same cookie to every other tenant. Being authenticated does not mean being allowed in.
Resolve the tenant from the host, validate it, then check membership on every request:
// apps/app/lib/tenant.ts
const RESERVED = new Set(["www", "app", "api", "admin", "auth"]);
export function tenantFromHost(host: string | null) {
if (!host) return null;
const suffix = ".example.com";
if (!host.endsWith(suffix)) return null;
const slug = host.slice(0, -suffix.length);
if (!slug || slug.includes(".") || RESERVED.has(slug)) return null;
return slug;
}
Then, in every protected read or write:
const session = await requireSession(returnTo);
const tenant = tenantFromHost((await headers()).get("host"));
if (!tenant || !(await isMember(session.userId, tenant))) {
notFound(); // or redirect to a "no access" page
}
Never trust a tenant identifier supplied by the client, and do not rely on the proxy alone for tenant isolation.
Security considerations when cookies span subdomains
Sharing a cookie widens the trust boundary from one hostname to your whole domain. These are the areas to review.
CSRF is not solved by SameSite alone
SameSite=Lax and even Strict allow cookies on requests between subdomains, because those are the same site. A page on a compromised or less-trusted subdomain can trigger authenticated requests to your main app. Defenses include:
Verifying the Origin header against an allowlist for state-changing requests.
Using anti-CSRF tokens for form posts and non-idempotent calls.
Using Server Actions, which compare the Origin header to the host by default. If you run behind a proxy or from a different origin, configure serverActions.allowedOrigins deliberately and keep the list short.
Your weakest subdomain sets the security level
If blog.example.com runs an outdated plugin, an XSS bug there can attack users of app.example.com through cookie tossing or authenticated requests. Before sharing a cookie, inventory every subdomain and everything that runs on it.
Cookie tossing and overwriting
A sibling subdomain can set a cookie with Domain=example.com and the same name, shadowing or replacing yours. Mitigations:
Use the __Host- prefix for any cookie that does not need to be shared, since it cannot be overwritten from a sibling.
Sign or encrypt shared values and verify them strictly.
Fail closed: if verification fails, treat the user as signed out.
Subdomain takeover
A DNS record that still points at a deleted cloud resource lets someone else claim that hostname. That hostname receives your shared cookie. Audit DNS regularly, remove stale CNAME records, and decommission services in the correct order: remove DNS first, then the resource.
Isolate user-generated content
Never serve user uploads or customer-supplied HTML from a subdomain that receives your session cookie. Use a separate registrable domain for that content, so a malicious file cannot read or abuse the session.
Session lifecycle
Fixation: issue a fresh session ID at sign-in, as the code above does with crypto.randomUUID().
Expiry: set a finite lifetime and consider a sliding or refresh strategy.
Revocation: a pure stateless JWT cannot be revoked before it expires. If you need immediate logout everywhere, store the sid in a database or cache and check it, or keep tokens short-lived with a refresh mechanism.
Logout: clear the cookie with identical name, domain and path, and invalidate the server-side record if you have one.
HttpOnly, Secure and an explicit SameSite on the session cookie
__Secure- or __Host- prefix in production
Long, random SESSION_SECRET stored in a secrets manager
Verification of algorithms, issuer and audience
Redirect targets validated against an allowlist
Origin checks or CSRF tokens on state-changing requests
CORS allowlist with credentials, never *
Every subdomain inventoried and DNS audited
User-generated content on a separate registrable domain
Authorization checked near the data, not only in the proxy
Logout tested across all subdomains
Caching and per-user data
Authentication adds a caching risk: a response personalized for one user must never be served to another. A few habits help:
Send Cache-Control: private (or no-store) on responses that depend on the session.
Add Vary: Cookie where a shared cache could otherwise mix users.
Do not put per-user data into shared caches or statically generated output.
Next.js caching has its own behavior, which is covered in our deep-dive on Next.js fetch caching, the Data Cache and revalidateTag. The Next.js documentation also describes authentication with Cache Components, which is worth reading if you use that feature.
Testing your setup
Verify behavior with checks you can repeat:
Inspect the cookie. In your browser's developer tools, open Application → Cookies. Confirm the Domain column shows example.com, and that HttpOnly, Secure and SameSite are set as intended.
Check the header. Request your sign-in endpoint with curl -i and read the Set-Cookie line.
Cross-subdomain read. Sign in on one subdomain, then open another and confirm you are recognized without a new login.
Logout everywhere. Sign out on one subdomain and refresh the others. Each should treat you as anonymous.
Redirect safety. Try a returnTo pointing at a host outside your allowlist and confirm it falls back to the default.
CORS preflight. Confirm that an allowed origin gets credentials headers and that an unknown origin gets none.
Expiry. Shorten the lifetime in a test environment and confirm expired sessions are rejected.
Automate the important ones. Add integration tests for sign-in, logout, redirect validation and the tenant membership check.
Troubleshooting common problems
Symptom
Likely cause
Fix
Session works on one subdomain only
Cookie set without Domain, so it is host-only
Set Domain=example.com through AUTH_COOKIE_DOMAIN
Cookie never appears in the browser
Secure cookie set over plain HTTP, or a __Secure- name without HTTPS
Use HTTPS, or use unprefixed names in development
Works locally, fails in production
AUTH_COOKIE_DOMAIN or SESSION_SECRET differs between projects
Make environment variables identical across apps
Logout does not clear other subdomains
Cookie cleared with different domain or path
Clear with the same name, domain and path
fetch to the API shows a CORS error
Missing credentials: "include", or Allow-Origin: *
Echo an allowed origin and add Allow-Credentials: true
Token decryption or signature errors
Different secret or cookie name between apps
Use one shared secret and one shared cookie name
Redirect loop between apps
Proxy matcher includes the login route
Exclude the login path from the matcher
Cookies on *.vercel.app not shared
vercel.app is a public suffix
Use a custom domain you own
Users see each other's data
Per-user response cached publicly
Use Cache-Control: private and review caching
Cookie too large
Payload holds too much data
Keep only a session ID and user ID in the token
Frequently asked questions
Do I need the leading dot in the cookie domain?
No. Under RFC 6265, a leading dot is ignored, so example.com and .example.com behave identically in modern browsers.
Can I share a session between example.com and example.org?
Not with a cookie. They are different registrable domains. Use Pattern 2, where a central auth host redirects users and each app creates its own session.
Is a shared parent-domain cookie secure enough?
It can be, if every subdomain is trusted and hardened. It increases the blast radius of a compromised subdomain, so use a central auth host with separate sessions when trust levels differ.
Should I use JWTs or database sessions?
Stateless JWTs are simple and scale easily but are hard to revoke. Database or cache-backed sessions allow immediate revocation at the cost of a lookup. Many teams combine a short-lived token with a server-side record.
Does SameSite=Strict protect me between subdomains?
No. Subdomains of the same registrable domain are the same site, so cookies are still sent. Add Origin checks or CSRF tokens.
Does this work with the Next.js Pages Router?
Yes. The cookie rules are the same, and you set the cookie from an API route with Set-Cookie. The App Router examples above use cookies() from next/headers.
Why does it work on localhost but not in production?
Local testing often uses host-only cookies on a single host. Production adds a real domain, HTTPS, prefixes and multiple apps. Reproduce this locally with hostnames under a development domain.
Conclusion
Next.js authentication across multiple subdomains comes down to a handful of decisions. Choose where the session lives and who may read it. Scope the cookie with the Domain attribute only when you truly want every subdomain to receive it. Keep verification centralized, and apply the same cookie settings everywhere. Then treat the extra exposure seriously with Origin checks, redirect validation, subdomain hygiene and per-tenant authorization.
For a small set of trusted apps owned by one team, a shared __Secure- cookie signed with a common secret is practical and easy to reason about. As soon as trust levels diverge, move sign-in to a central host and give each app its own host-only session.
Whichever pattern you pick, test it across real hostnames before launch, and revisit the checklist whenever you add a new subdomain.
Secure Password Generator for strong random strings generated locally in your browser (for production secrets, a command-line generator such as openssl is also a good option)