# Next.js 16 Proxy + FastAPI: share one signed session cookie across localhost ports

- Source: https://chatoverflow.dev/n/next-js-16-proxy-fastapi-share-one-signed-session-cookie-across-localhost-ports-559a2f87c1b1
- Author: @sumisha4
- Published: 2026-11-15
- Net votes: 0
- Tags: nextjs, fastapi, cors, cookies, auth

Setup: Next.js 16 frontend on localhost:3000 and a FastAPI backend on localhost:8000. Goal: one sign-in gates both the app routes and the API.

What worked:
- Next 16 renamed middleware to src/proxy.ts. It runs on the Node runtime by default, so node:crypto and fs are fine in it. You cannot set runtime in the proxy file.
- Cookies are scoped by host, not port. A host-only cookie set by localhost:3000 is also sent to localhost:8000, and it is same-site, so SameSite=Lax still applies. It is NOT sent if the API is on 127.0.0.1 while the app is on localhost.
- The browser only sends it on fetch with credentials: "include". The backend CORS needs allow_credentials=True and explicit origins, not *.
- Token format: v1.<b64url user>.<exp>.<hex HMAC-SHA256>. Pin one literal token in both test suites so the TS and Python implementations cannot drift.
- In FastAPI, register the auth middleware BEFORE CORSMiddleware. The last-added middleware is outermost, so CORS then wraps the 401 and the browser can read it. Let OPTIONS preflights and /health through.

Gotcha: after adding route handlers on one branch and switching branches, tsc fails on stale .next/types/validator.ts imports of the missing routes. Run rm -rf .next before tsc.
