You need to check incoming requests against a session store, validate JSON Web Tokens, and trigger background refreshes if a token is about to expire. Doing this inside edge middleware intercepts requests before they hit your rendering pipeline. Unauthorized users stay out of protected routes entirely. You can read more about how this complements API setups by reviewing our guide on App Router authentication patterns with a Laravel API.
The main trap when writing edge middleware for auth is latency. If your middleware makes a synchronous blocking network request to an upstream database on every single page view, your time-to-first-byte climbs rapidly. Instead, you'll want to decode cryptographically signed tokens directly at the edge. Only hit your refresh endpoint when the token has crossed a specific time threshold. It's a delicate balance between security and raw throughput.
You aren't dealing with a traditional Node.js runtime here. Edge functions execute in a V8 isolate environment, which means you cannot rely on standard Node.js crypto modules or native filesystem bindings. You'll use Web Crypto APIs available globally in the edge runtime, limiting which third-party packages you can import. If you need background token refreshing, you have to detect an expiring session cookie, send a fetch request to your upstream authentication service, and attach the newly minted tokens to the outgoing response headers before the browser finishes rendering.
To avoid infinite redirect loops during token renewal, your matcher config needs to explicitly exclude static assets, login pages, and internal API routes. If you trip up on this configuration, consult the troubleshooting steps in fixing Next.js middleware redirect loops to straighten out your matcher rules. Don't skip this step. You'll quickly trap your users in a browser redirection cycle.
Designing the Edge Middleware Architecture
Here is a complete middleware implementation that validates a cookie-backed access token, checks its expiration, and requests a rotation when it nears the end of its lifespan. We'll use the jose library because it's built specifically to run in edge runtimes without relying on Node.js core modules. You can inspect the design constraints directly in the Next.js middleware documentation to ensure your setup adheres to framework standards.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET_KEY || 'fallback_secret_key_change_me'
);
export async function middleware(request: NextRequest) {
const accessToken = request.cookies.get('access_token')?.value;
const refreshToken = request.cookies.get('refresh_token')?.value;
const loginUrl = new URL('/login', request.url);
if (!accessToken) {
if (!refreshToken) {
return NextResponse.redirect(loginUrl);
}
return await handleTokenRefresh(request, refreshToken);
}
try {
const { payload } = await jwtVerify(accessToken, SECRET_KEY);
const expiresAt = (payload.exp as number) * 1000;
const fiveMinutes = 5 * 60 * 1000;
if (Date.now() > expiresAt - fiveMinutes && refreshToken) {
return await handleTokenRefresh(request, refreshToken);
}
const response = NextResponse.next();
response.headers.set('x-user-id', String(payload.sub));
return response;
} catch (error) {
if (refreshToken) {
return await handleTokenRefresh(request, refreshToken);
}
return NextResponse.redirect(loginUrl);
}
}
async function handleTokenRefresh(request: NextRequest, refreshToken: string) {
const loginUrl = new URL('/login', request.url);
try {
const response = await fetch(`${request.nextUrl.origin}/api/auth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cookie': `refresh_token=${refreshToken}`
},
});
if (!response.ok) {
const clearSessionResponse = NextResponse.redirect(loginUrl);
clearSessionResponse.cookies.delete('access_token');
clearSessionResponse.cookies.delete('refresh_token');
return clearSessionResponse;
}
const data = await response.json();
const nextResponse = NextResponse.next();
nextResponse.cookies.set({
name: 'access_token',
value: data.access_token,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
});
return nextResponse;
} catch (err) {
return NextResponse.redirect(loginUrl);
}
}
export const config = {
matcher: [
'/dashboard/:path*',
'/settings/:path*',
'/api/protected/:path*',
],
};That script handles the core token lifecycle inside the edge runtime. It reads incoming cookies, verifies cryptographic signatures without querying a database, and silently triggers a refresh when the expiration window gets too close. You'll also want to review the security guidelines provided by the jose library repository to understand how token encryption algorithms behave under memory constraints.
Handling Failures and Edge Limits
Running code at the edge introduces unique constraints that differ from standard server deployments. The V8 worker terminates execution if it exceeds CPU time limits, meaning you can't run heavy cryptographic loops or synchronous database queries inside your middleware block. If your upstream auth server goes down, your token refresh call throws a network error, which forces you to catch the exception and redirect the user back to the login screen. You should also review practices for preventing middleware cache poisoning to ensure your authenticated response headers don't get trapped in shared CDN caches.
When debugging middleware authentication issues, you'll typically encounter a few specific error messages in your terminal or browser console. Understanding what triggers these errors helps you fix configuration drift quickly.
You might spot ERR_JWT_EXPIRED thrown by the verification library when the token timestamp exceeds the current system time. Handle this by falling back to your refresh token flow instead of dropping the user session immediately. Another common culprit is TypeError: fetch failed, which occurs when your edge function attempts to make an internal API call using a relative URL or when the upstream auth server is completely unreachable. Always construct absolute URLs using request.nextUrl.origin to prevent this specific failure mode.
You'll also run into Edge Runtime unsupported API if you accidentally import Node.js built-ins like fs, crypto, or path inside your middleware file. Stick strictly to web-standard APIs and edge-compatible packages. If a third-party library tries to read environment variables via process.env in a non-standard way, the edge bundler will throw a syntax error during compilation. Don't ignore these build warnings, because they indicate runtime failures waiting to happen in production.
Verifying the Implementation
You can verify your token rotation flow by inspecting the application storage tab in your browser developer tools while navigating through protected routes. When your access token approaches its expiration window, the network tab should show an internal background call to your refresh handler, followed by an immediate update to the access_token cookie value without requiring a full page reload.
To test this locally, spin up your development server with standard terminal commands and check the output for any runtime warnings regarding unsupported modules. Here's how you install the required dependency before running your verification suite.
npm install joseAfter installing the package, run your test suite or manually click through your protected dashboard routes. You'll know the middleware works correctly when expired access tokens trigger a silent background refresh rather than an unexpected kick to the login page. It's a solid pattern that keeps your backend secure while maintaining a smooth user experience.












