Next.js Auth Middleware: JWTs, Roles, and Refresh
Middleware runs before a request reaches your pages and route handlers, which makes it the natural gatehouse for authentication. It can redirect anonymous visitors away from private routes, reject API calls without a valid token, and attach the verified user identity to request headers that Server Components read without re-parsing the cookie. The same position makes it a common source of subtle security bugs: middleware in Next.js runs on the Edge runtime, request headers set in middleware are not automatically trusted by your pages, and an expired access token is not itself proof that the user should be logged out.
It helps to separate what middleware is from what it is not. It is an early filter: cheap, global, and excellent at refusing obviously invalid traffic before your page code allocates a single query. It is not an authorization system of record. Because matchers can be misconfigured and because direct clients can call route handlers without ever passing through your UI, the definitive check for any protected resource must live as close to the data as the route itself. Teams that treat middleware as the only gate ship features that work in the browser and leak through a crafted POST. Teams that treat it as a performance and UX layer â redirecting the user to login early, attaching identity for convenience â get fast refusals without giving up defense in depth.
This lesson builds a middleware that handles public routes, protected pages, role-gated sections, and silent token refresh â then shows how to carry the verified identity the rest of the way into your data layer.
Prerequisites
- !Comfort writing Next.js middleware
- !Basic understanding of JWT claims and expiry
- !A session strategy using httpOnly cookies
What You'll Learn
- 1Structure a middleware matcher around public and protected route groups
- 2Verify JWT signatures on the Edge runtime without Node-only libraries
- 3Enforce role checks for admin areas
- 4Forward verified identity to Server Components through request headers
The shape of a gatehouse
A clean middleware separates four decisions: is this path public, is a token present, is the token valid, and does the user's role allow the destination. Keeping those questions distinct makes the logic testable and prevents the all-too-common boolean blob where one wrong comparison quietly opens every route.
// middleware.js
import { NextResponse } from 'next/server';
import { verifyAccessToken } from './lib/auth-edge';
const PUBLIC_PATHS = ['/login', '/register', '/api/auth', '/_next', '/favicon.ico'];
function isPublic(pathname) {
return PUBLIC_PATHS.some((p) => pathname.startsWith(p));
}
export async function middleware(request) {
const { pathname } = request.nextUrl;
if (isPublic(pathname)) {
return NextResponse.next();
}
const token = request.cookies.get('accessToken')?.value;
if (!token) {
return redirectToLogin(request);
}
let payload;
try {
payload = await verifyAccessToken(token);
} catch {
return redirectToLogin(request);
}
if (pathname.startsWith('/admin') && payload.role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-user-id', payload.sub);
requestHeaders.set('x-user-role', payload.role);
return NextResponse.next({ request: { headers: requestHeaders } });
}
function redirectToLogin(request) {
const login = new URL('/login', request.url);
login.searchParams.set('from', request.nextUrl.pathname);
return NextResponse.redirect(login);
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
Two details matter here. The matcher excludes static assets so the middleware does not tax every font and image request. And redirecting with a from parameter lets the login page return the user to where they were headed instead of dumping everyone on the homepage.
Verifying tokens on the Edge runtime
Middleware defaults to the Edge runtime, which has no access to the Node crypto module. The jsonwebtoken package will not work there; use jose, which implements Web Crypto and ships a small Edge-compatible build. Keep the secret in an environment variable and always specify the algorithm explicitly so a token signed with none cannot be accepted.
// lib/auth-edge.js
import { jwtVerify, SignJWT } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
export async function verifyAccessToken(token) {
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
issuer: 'acme-auth',
audience: 'acme-app',
});
return payload;
}
export async function signAccessToken({ sub, role }) {
return new SignJWT({ role })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(sub)
.setIssuer('acme-auth')
.setAudience('acme-app')
.setIssuedAt()
.setExpirationTime('15m')
.sign(secret);
}
Short access-token lifetimes are deliberate: a stolen token expires quickly, and the refresh token below re-issues it. The audience and issuer checks prevent a token minted for another service from being replayed against this one.
Carrying identity past the middleware
Headers injected by middleware reach Server Components through the request, but nothing stops a client from sending the same header names directly to your origin. Treat x-user-id as untrusted input unless you strip incoming copies first. Overwriting the header in middleware guarantees the value your pages read is the one you computed.
// Inside middleware, before forwarding
const requestHeaders = new Headers(request.headers);
requestHeaders.delete('x-user-id');
requestHeaders.delete('x-user-role');
requestHeaders.set('x-user-id', payload.sub);
requestHeaders.set('x-user-role', payload.role);
// app/admin/page.js
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
export default async function AdminPage() {
const headerStore = await headers();
const role = headerStore.get('x-user-role');
if (role !== 'admin') {
redirect('/unauthorized');
}
const stats = await loadAdminStats();
return <AdminDashboard stats={stats} />;
}
Middleware is a performance optimization for redirecting early; the page-level check is the security boundary. Defense in depth means an attacker who somehow bypasses the matcher still hits a hard refusal in the route itself.
Refreshing sessions without a flash of the login page
An expired access token during navigation should not dump a still-authenticated user on the login screen. When verification fails, attempt a refresh using the refresh-token cookie, mint a new access token, and set it on the response before continuing. Refresh tokens should be long-lived, stored in an httpOnly cookie, and rotated on every use so a leaked refresh token has a narrow window.
// Fragment of middleware.js refresh branch
try {
payload = await verifyAccessToken(token);
} catch {
const refreshToken = request.cookies.get('refreshToken')?.value;
if (!refreshToken) {
return redirectToLogin(request);
}
const session = await refreshSession(refreshToken);
if (!session) {
return redirectToLogin(request);
}
const response = NextResponse.next();
response.cookies.set('accessToken', session.accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 900,
});
response.cookies.set('refreshToken', session.refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/api/auth',
maxAge: 60 * 60 * 24 * 30,
});
return response;
}
If the refresh call throws â network error, revoked token, user deleted â fall through to the login redirect. Never let a failed refresh continue with the old, invalid cookie; that produces redirect loops that look like an outage.
Matcher configuration and static asset traffic
The matcher config decides which requests pay the middleware tax at all. A matcher that matches everything runs your verification logic for fonts, images, and framework internals that were never going to be protected, adding latency to every static asset on the page. The negative lookahead pattern shown earlier â excluding the framework's static and image paths â is the standard starting point, and it can be tightened further once your public route groups are known.
Testing the matcher is straightforward and worth doing deliberately. After a deploy, load a public page and a private page with the network panel open: the private request should redirect when unauthenticated and return normally when the cookie is valid. Static assets should show no middleware involvement at all â if your font files carry a Set-Cookie header or a redirect, the matcher is too broad. Route handlers under the api segment often need their own matcher entry, since a pattern scoped only to page paths silently leaves the API uncovered.
One subtlety with the Edge runtime is environment variable inlining. A JWT secret that exists only in the runtime environment of a serverless function can be undefined inside middleware compiled for the Edge bundle; the variable must be present in the build environment as well, or verification will mysteriously fail only in production. This class of bug presents as a login loop that never reproduces locally, and the fix is usually a one-line addition to the deployment's build-time environment configuration rather than any change to the verification code.
Protecting API routes too
Pages are not the only surface. Route handlers under app/api must re-verify tokens themselves because middleware matchers can be misconfigured and because direct API consumers may skip your UI entirely. A shared helper keeps the rules in one place: read the cookie, verify the signature, check the role, return a typed 401 or 403 instead of a redirect, since API clients cannot follow HTML redirects meaningfully.
| Request shape | Middleware behavior | Route handler behavior |
|---|---|---|
| Public page, no cookie | Continue | Not applicable |
| Private page, valid token | Attach headers, continue | Read headers or re-verify cookie |
| Private page, expired token | Refresh, then continue | Reject if middleware was bypassed |
| Admin page, non-admin role | Redirect to /unauthorized | Return 403 JSON |
| API call, no token | Continue if matcher excludes it | Return 401 JSON |
The table is the contract your team should write down. Every new route group gets classified against it during review, which prevents the slow drift where one forgotten prefix quietly ships unauthenticated.
Common Mistakes
Trusting x-user-id headers set by the client
Fix: Delete incoming copies of your identity headers in middleware before writing the verified values.
Using jsonwebtoken or Node crypto inside middleware
Fix: Switch to jose, which runs on Web Crypto and supports the Edge runtime.
Redirecting API requests to a login HTML page
Fix: Return 401 or 403 JSON from route handlers; redirects are only meaningful for document navigations.
Long-lived access tokens to avoid refresh logic
Fix: Keep access tokens short and implement refresh; a stolen fifteen-minute token is far less valuable than a stolen thirty-day one.
Best Practices
- Deny by default: classify every route as public or protected during code review
- Strip incoming identity headers, then set your own before forwarding the request
- Re-check authorization inside the page or handler, not only in middleware
- Rotate refresh tokens on use and scope their cookie path to the auth endpoints
Interview Questions
Q1: Why can't I use the jsonwebtoken package in Next.js middleware?
Middleware runs on the Edge runtime without Node crypto. jose implements JWT operations with Web Crypto and works there.
Q2: Are x-user-id headers from middleware trustworthy?
Only if you delete any client-supplied copies first. Otherwise a caller can set the header directly and impersonate a user.
Q3: How should an expired token be handled for a logged-in user?
Attempt a refresh with the refresh-token cookie; on success set new cookies and continue, on failure redirect to login with a from parameter.
Key Takeaways
- Middleware is an early gate, not the security boundary â pages and handlers still verify.
- Edge compatibility rules out Node crypto; jose is the standard JWT library there.
- Role checks and header stripping must happen before any protected content is composed.
- Silent refresh on verification failure prevents false logouts without weakening expiry.
- API routes return 401 or 403 JSON rather than following HTML redirects.