How to Implement JWT Auth in Next.js Middleware
Protect Next.js routes with edge-compatible JWT verification using jose, HttpOnly cookies, safe redirects, request headers, CSRF checks, and defense in depth.
On this page
Introduction
Next.js middleware runs before a request reaches a page, route handler, or server action. That makes it a convenient place to reject unauthenticated requests early, redirect browser navigation to a login page, and attach identity information to the request. It is not a complete authorization layer, and treating it as one is the most common mistake in Next.js authentication code.
This tutorial implements a custom JWT session with jose, a library that uses Web Crypto and works in the Edge runtime. It covers token issuance, cookie flags, middleware matching, redirect safety, header spoofing, and the second verification that sensitive server code still needs. The examples assume the App Router and a recent Next.js release. If you prefer a maintained session framework, Auth.js is a reasonable alternative; the security boundaries discussed here still apply.
Create and verify tokens with jose
Install jose. Do not use jsonwebtoken in middleware unless you have confirmed that the runtime provides its Node crypto dependencies:
npm install jose
Keep the signing secret in a server-only environment variable. The NEXT_PUBLIC_ prefix exposes a value to the browser, so never use it for a JWT secret. A helper module can own signing and verification:
// lib/auth.ts
import { SignJWT, jwtVerify } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const issuer = 'example-web';
const audience = 'example-api';
if (!process.env.JWT_SECRET) {
throw new Error('JWT_SECRET is required');
}
export async function signSession(userId: string): Promise<string> {
return new SignJWT({ sub: userId })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setIssuer(issuer)
.setAudience(audience)
.setExpirationTime('15m')
.sign(secret);
}
export async function verifySession(token: string) {
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
issuer,
audience,
});
return payload;
}
jwtVerify validates exp and nbf by default and rejects an algorithm that is not in the allowlist. Always pass algorithms; accepting the algorithm from the token header enables algorithm-confusion attacks. The secret must be a long random value, not a human-readable passphrase.
A 15-minute access token is intentionally short. Browser sessions usually need a refresh mechanism. Either issue a separate refresh token stored server-side, or use a server-side session store and let the cookie hold an opaque session id. A stateless JWT cannot be revoked immediately; if logout must invalidate a stolen token, you need a denylist or server-side session state.
Gate routes in middleware
Create middleware.ts at the project root or under src/. The matcher limits which requests run through the function:
// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
import { verifySession } from './lib/auth';
const PUBLIC_API = new Set(['/api/auth/login', '/api/auth/refresh']);
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (PUBLIC_API.has(pathname)) {
return NextResponse.next();
}
const token = request.cookies.get('__Host-session')?.value;
if (!token) {
return reject(request, pathname);
}
try {
const payload = await verifySession(token);
const userId = typeof payload.sub === 'string' ? payload.sub : null;
if (!userId) return reject(request, pathname);
const headers = new Headers(request.headers);
headers.delete('x-user-id');
headers.set('x-user-id', userId);
headers.set('x-user-verified', 'middleware');
return NextResponse.next({ request: { headers } });
} catch {
return reject(request, pathname);
}
}
function reject(request: NextRequest, pathname: string) {
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const login = new URL('/login', request.url);
login.searchParams.set('next', pathname + request.nextUrl.search);
return NextResponse.redirect(login);
}
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*', '/api/private/:path*'],
};
API requests receive a 401 JSON response instead of an HTML redirect, which clients can handle correctly. Page requests are redirected to login. The next parameter preserves the destination, but it must be validated when login completes; accepting any string allows an open redirect to another origin.
The request-header approach deserves care. NextResponse.next({ request: { headers } }) forwards the modified headers to server components and route handlers. Delete any client-supplied x-user-id before setting it, otherwise a client could inject an identity header. The header is still only a convenience: downstream code must treat it as an assertion from middleware, not as a signed token, and must not use it for authorization without a second verification.
Middleware matching is easy to get wrong. If the matcher includes /_next/static or public assets, every asset request pays for token verification. If it misses a protected route, no gate runs. Keep the matcher explicit and add a test that enumerates the protected routes. Middleware is not a substitute for checks inside route handlers: a configuration change or a new route outside the matcher can silently bypass it.
Set cookies securely on login
The login route verifies credentials and sets a cookie. Use HttpOnly, Secure, SameSite, Path=/, and a bounded Max-Age. The __Host- prefix requires Secure, Path=/, and no Domain, which prevents a subdomain from overwriting the cookie:
// app/api/auth/login/route.ts
import { NextResponse } from 'next/server';
import { signSession } from '@/lib/auth';
import { verifyPassword } from '@/lib/users';
export async function POST(request: Request) {
const { email, password } = await request.json();
const user = await verifyPassword(email, password);
if (!user) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const token = await signSession(user.id);
const response = NextResponse.json({ user: { id: user.id, name: user.name } });
response.cookies.set('__Host-session', token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 15,
});
return response;
}
Use SameSite=Strict for high-risk administrative applications if the user experience allows it; Lax is a common default for general applications. Neither value replaces CSRF protection. For cookie-authenticated state-changing requests, verify the Origin header against an allowlist or require a CSRF token. A cross-site form can send a POST with cookies under some conditions, and a JSON API should reject requests whose origin is not trusted.
Logout deletes the cookie, but deletion does not revoke an already stolen token. Combine short access-token lifetimes with a server-side refresh session, and invalidate the refresh session on logout or password change. If immediate access-token revocation is required, maintain a small denylist keyed by jti with a TTL equal to the token lifetime.
Refresh without weakening the session
A refresh endpoint should accept a refresh token only from an HttpOnly cookie, validate rotation, and set a new access cookie. Store refresh tokens hashed with a family id and revoke the family when a previously rotated token is reused. Do not return refresh tokens in a JSON body that JavaScript can read; that reintroduces the XSS exposure the HttpOnly cookie was meant to prevent.
Keep the refresh endpoint outside the middleware matcher or explicitly allow it in the public set, and protect it with the same origin check as other mutations. Rate-limit login, refresh, and password-reset endpoints. An unthrottled login endpoint is a credential-stuffing target regardless of how strong the JWT implementation is.
Re-check in server code
Middleware should be the first gate, not the only one. In a server component or route handler that reads or mutates a specific resource, verify the session again and check ownership:
import { cookies } from 'next/headers';
import { verifySession } from '@/lib/auth';
export async function getOwnedProject(projectId: string, userId: string) {
const project = await db.project.findUnique({ where: { id: projectId } });
if (!project || project.ownerId !== userId) return null;
return project;
}
The x-user-id header is useful for logging and for avoiding duplicate parsing, but authorization decisions need the actual user id and the resource’s owner. A user with a valid token can still request another user’s project id. This is the difference between authentication and authorization, and middleware cannot make the latter decision without loading the resource.
If middleware sets an identity header, strip it at the outermost boundary and document that trust. Do not expose a public API route that echoes the header or forwards it to an internal service without authentication. In a multi-tenant application, include the tenant id in the token and verify it against the resource.
Test the protected paths
Add end-to-end tests with Playwright for the full cookie flow: log in, visit a protected page, log out, and confirm the redirect. For a missing cookie, assert the redirect target includes a safe next value. For an expired token, craft a token with a past exp using the test secret and confirm the 401 or redirect.
Also test that a client-supplied x-user-id header does not survive into a protected server component, and that an API request without a token returns JSON rather than an HTML redirect. Those two cases catch header spoofing and content negotiation regressions that a simple “logged in” test misses.
Common pitfalls
- Using
NEXT_PUBLIC_for the secret. It ships to the browser. - Trusting middleware for authorization. It does not know resource ownership.
- Not deleting spoofed identity headers. A client can send
x-user-iditself. - Redirecting API calls to HTML. API clients need a 401 JSON response.
- An open redirect in
next. Validate that the destination is a local path. - Long-lived access tokens without revocation. Logout does not invalidate them.
- No CSRF defense. SameSite is not sufficient by itself.
- Using
jsonwebtokenat the edge. It may depend on unsupported Node APIs.
Conclusion
Next.js middleware with jose is a useful first gate: it rejects missing or invalid sessions before rendering, keeps protected routes out of the public bundle path, and can pass a verified user id to server code. It is not a complete authentication system. Secure cookies, refresh rotation, origin checks, per-resource authorization, and a second verification in sensitive handlers are all part of the design. Treat each boundary explicitly, and the middleware becomes a performance and UX improvement rather than a security assumption.
Sources: Next.js middleware documentation, jose documentation, OWASP CSRF prevention cheat sheet.
FAQ
- Can Next.js middleware replace authorization checks in API routes?
- No. Middleware is a coarse gate that runs before routing. A route handler or server action that performs a sensitive operation must still verify the session and check authorization, because middleware can be bypassed by configuration mistakes and does not know resource ownership.
- Why use jose instead of jsonwebtoken in middleware?
- Middleware can run in the Edge runtime, which does not provide all Node.js crypto APIs that jsonwebtoken depends on. jose uses Web Crypto and works in both Edge and Node runtimes.
- Is SameSite enough to prevent CSRF?
- SameSite reduces risk but is not a complete CSRF defense across all browsers and deployment topologies. For cookie-authenticated mutations, also check the Origin or Sec-Fetch-Site header, or use a CSRF token tied to the session.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.