Next.js cookies for auth when the API is on another domain
The API set a cookie, but Next.js couldn't see a session. How I handled domain scope, Route Handler cookies and logged-in local development.
Login worked on staging, but locally the next page load threw me back to the login screen. The browser stored the API's cookie, but it belonged to the API's host and requests to the Next.js frontend never included it. The project was a SaaS dashboard with a Next.js App Router frontend calling a separate auth API. Names and domains in the code are changed.
The API's host-only cookie stays with the API
When api.example.com returns Set-Cookie without Domain, the cookie is scoped to api.example.com only. Requests to app.example.com don't include it, so proxy, Server Components and Route Handlers can't read the session.
The API could set Domain=example.com, but that needs both apps under one parent domain and sends the session to matching subdomains. I had Next.js set its own first-party cookie and call the API server to server instead. It works when the domains are completely different, and the API keeps its strict CORS policy.
Set the cookie in a Route Handler
Our backend ran the OAuth redirect flow itself and /api/login just forwarded it. With an API that returns a token as JSON, it looks like this:
// app/api/login/route.ts
import { NextResponse, type NextRequest } from 'next/server'
const API_URL = process.env.API_URL // server-only, no NEXT_PUBLIC_ prefix
export async function POST(request: NextRequest) {
const { email, password } = await request.json()
const apiRes = await fetch(`${API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
})
if (!apiRes.ok) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 })
}
const { accessToken, expiresIn } = await apiRes.json()
const res = NextResponse.json({ ok: true })
res.cookies.set('session', accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: expiresIn, // seconds
})
return res
}
A Server Action uses (await cookies()).set('session', token, options). cookies() has been async since Next.js 15, and every example here uses await so it runs on 15 and 16.
When forwarding the API's Set-Cookie, use headers.getSetCookie(). headers.get('set-cookie') joins cookies with commas, and expiry dates contain commas too. A forwarded cookie that still says Domain=api.example.com gets rejected, because a response from app.example.com can only set cookies for its own host or a parent domain.
A Server Component can read cookies but can't write them, since it renders while the response streams and the headers are already gone. Writes belong in Server Functions, Route Handlers and proxy, so a page that finds a broken session has to hand the cleanup to one of those.
On the attributes: httpOnly keeps an XSS bug from copying the token out, and sameSite: 'lax' sends the cookie on a link from outside but not on cross-site POSTs or fetches. I leave domain out for the narrowest scope and match maxAge (in seconds) to the token's lifetime. In production, consider the __Host- prefix. The browser then refuses the cookie without Secure and Path=/, or with a Domain, so a bad deploy can't widen its scope.
Proxy does a cheap check, the API does the real one
Proxy (proxy.ts since Next.js 16, middleware.ts before) runs on every matched route, prefetches included. Use it only for a cheap "is there a cookie at all" check:
// proxy.ts (middleware.ts before Next.js 16)
import { NextResponse, type NextRequest } from 'next/server'
const PROTECTED = ['/dashboard', '/settings']
export function proxy(request: NextRequest) {
const session = request.cookies.get('session')?.value
const { pathname } = request.nextUrl
if (!session && PROTECTED.some((p) => pathname.startsWith(p))) {
const url = new URL('/login', request.url)
url.searchParams.set('next', pathname)
return NextResponse.redirect(url)
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}
A server-side fetch doesn't pick up the browser's cookies, even with credentials: 'include'. The real check forwards the token to the API:
// lib/api.server.ts
import 'server-only'
import { cookies } from 'next/headers'
export async function apiFetch(path: string, init: RequestInit = {}) {
const token = (await cookies()).get('session')?.value
const headers = new Headers(init.headers)
if (token) headers.set('Authorization', `Bearer ${token}`)
return fetch(`${process.env.API_URL}${path}`, {
...init,
headers,
cache: 'no-store', // per-user data must never be shared
})
}
The helpers on that project sent both Authorization: Bearer and a Cookie header, which hid which one the API checked. Pick one. Expiry and refresh are covered in access and refresh tokens in the App Router.
Logout has to match the attributes it was set with
A delete only hits the cookie with the same name, path, domain and protocol it was set with. Otherwise the cookie stays, with no error from the browser. I changed the project's logout route 6 times in one day over this. response.cookies.delete('session') didn't remove it, so the next version built Set-Cookie by hand with Domain set to the parent domain, and that got rewritten again the same day. My guess from the code is that the cookie was set with a Domain and the delete wasn't, but I haven't reproduced it.
// app/api/logout/route.ts
import { NextResponse, type NextRequest } from 'next/server'
export async function POST(request: NextRequest) {
const token = request.cookies.get('session')?.value
if (token) {
// No browser cookies here: forward the token explicitly
await fetch(`${process.env.API_URL}/auth/logout`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
}).catch(() => {})
}
const res = NextResponse.json({ ok: true })
res.cookies.set('session', '', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 0,
})
return res
}
The identity provider had a separate session, so logout then sent the browser to the API's logout URL. A server-side call can't touch cookies the browser stores for another domain.
httpOnly cookies on localhost
secure: process.env.NODE_ENV === 'production' is there because next dev serves plain HTTP, though current Chrome and Firefox accept Secure cookies on http://localhost. I keep the toggle because I haven't tested every browser. For real local HTTPS there's next dev --experimental-https.
Cookies aren't isolated by port, so two local projects with a session cookie overwrite each other. localhost and api.example.com are cross-site. The API's SameSite=Lax cookie isn't sent on a fetch from your local page, while SameSite doesn't apply when the Next.js server calls the API.
Borrowing a production session for local work
When the dev backend was down, I pointed the local frontend at the production API through .env.local. The middleware returned early in development, since the OAuth flow redirected to the deployed domain and couldn't come back to localhost. Then I copied the session cookie from a production tab onto localhost in the DevTools Application panel, because document.cookie can't create an httpOnly cookie. I toggled that early return with comments 6 times to test the middleware itself, and a dedicated environment variable would have been better.
If you keep a dev token in an environment variable, never give it a NEXT_PUBLIC_ prefix. Next.js inlines those into the browser bundle at build time, and no NODE_ENV check removes them.
A dev-only Route Handler can read DEV_SESSION_TOKEN from a git-ignored .env.local instead. I wrote this one for the post, not for the project:
// app/api/dev/session/route.ts
import { NextResponse, type NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const isLocal = request.nextUrl.hostname === 'localhost'
if (process.env.NODE_ENV !== 'development' || !isLocal) {
return new NextResponse(null, { status: 404 })
}
const token = process.env.DEV_SESSION_TOKEN
if (!token) {
return NextResponse.json({ error: 'DEV_SESSION_TOKEN is not set' }, { status: 400 })
}
const res = NextResponse.redirect(new URL('/', request.url))
res.cookies.set('session', token, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60, // one hour, then paste a fresh one
})
return res
}
Under next start, NODE_ENV is production and the route answers 404.
That copied value is a live bearer credential. Don't commit it, and use a test account, never an admin one. Requests from localhost write to production data, so I kept this to read-heavy UI work and logged out on production afterwards.
Staging with test accounts, a local backend in Docker or MSW mocks are all better for daily work. My pick is a Next.js rewrite. The browser only talks to localhost and the server calls whichever API is up, which is the same first-party, server-to-server setup as the fix at the top.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.