Next.js App Router + separate NestJS API: best way to handle JWT auth with httpOnly cookies? #213892
Replies: 3 comments
|
Hi @MohammedBajhaw, For your architecture, I'd recommend keeping authentication and token-refresh logic in NestJS and using Next.js as a Backend-for-Frontend (BFF) if you need authenticated Server Component requests. Here's how I'd approach it: 1. Browser requests vs Next.js Route Handlers You have two valid options:
Server-side I'd lean toward BFF if you want to centralize authentication and avoid exposing tokens to browser JavaScript. 2. Where should token refresh happen? I'd keep refresh logic in NestJS. For example: NestJS should:
Next.js middleware can help with routing or checking whether a session cookie exists, but it shouldn't be the authority for token validation or refresh. 3. Cookie configuration For your subdomain setup: These are different origins but normally the same site. For direct browser-to-API requests, a starting configuration would be: {
httpOnly: true,
secure: true,
sameSite: 'lax',
domain: 'example.com',
path: '/',
}Use Also, consider whether you actually need the 4. Important security considerations
My preferred architecture: One important distinction: if NestJS directly owns the cookies, the BFF must explicitly forward incoming cookies and correctly relay One question: Do you need authentication inside Next.js Server Components, or is your frontend primarily a client-side application that calls NestJS directly? That answer would help determine whether a full BFF is worthwhile or whether direct credentialed API requests are simpler. Useful references:
Hope this helps! |
|
Great answer from @Prasad-Pitke — just to add the practical bits that decide between the two options he laid out: Which one to pick: it comes down to whether your Server Components need the user. If they fetch user-specific data server-side (dashboard, settings pages), go BFF — your Route Handlers become the single place that attaches the token, and your client components never touch auth at all. If the app is mostly client components calling the API directly, the direct browser → NestJS route with Refresh in practice: keep it in NestJS, but don't put it in middleware. Middleware runs on the Edge and can't safely hold secrets or do the refresh dance — instead, have a Next.js Route Handler call One cookie gotcha: with |
|
The two answers above cover the architecture well, so here's the code side of the BFF route, since that's where most people get stuck. In a Route Handler, read the cookies and forward them yourself, then pass any // app/api/[...path]/route.ts
import { cookies } from 'next/headers';
const API = process.env.API_URL!; // https://api.example.com
async function proxy(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
const url = new URL(req.url);
const cookieHeader = (await cookies()).toString();
const res = await fetch(`${API}/${path.join('/')}${url.search}`, {
method: req.method,
headers: {
'content-type': req.headers.get('content-type') ?? 'application/json',
cookie: cookieHeader,
},
body: ['GET', 'HEAD'].includes(req.method) ? undefined : await req.text(),
cache: 'no-store',
});
const out = new Response(res.body, { status: res.status });
out.headers.set('content-type', res.headers.get('content-type') ?? 'application/json');
for (const c of res.headers.getSetCookie()) out.headers.append('set-cookie', c);
return out;
}
export { proxy as GET, proxy as POST, proxy as PUT, proxy as PATCH, proxy as DELETE };Two things to watch with this: On the NestJS side, read the token from the cookie instead of the Authorization header: // main.ts
app.use(cookieParser());
app.enableCors({ origin: 'https://app.example.com', credentials: true });
// jwt.strategy.ts
super({
jwtFromRequest: ExtractJwt.fromExtractors([(req) => req?.cookies?.access_token]),
secretOrKey: process.env.JWT_SECRET,
});CORS only matters if the browser also calls the API directly. If everything goes through the proxy, the browser never talks to api.example.com at all, so you could even keep the API off the public internet. |
Uh oh!
There was an error while loading. Please reload this page.
🏷️ Discussion Type
Question
Body
I'm building a Next.js (App Router) frontend that talks to a separate NestJS backend on a different subdomain (app.example.com -> api.example.com).
The NestJS API issues a short-lived access token and a refresh token. I want to keep both in httpOnly cookies, but I'm confused about a few things:
credentials: 'include'?/auth/refreshendpoint?SameSite/Domainsetup for cookies shared across subdomains?If anyone has a working pattern or an example repo, I'd really appreciate it. Thanks!
Guidelines
All reactions