Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_PATHS = ['/', '/login', '/register', '/api/auth'];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow public paths and static assets
if (
PUBLIC_PATHS.some((p) => pathname.startsWith(p)) ||
pathname.startsWith('/_next') ||
pathname.includes('.')
) {
return NextResponse.next();
}
const token = request.cookies.get('auth-token')?.value;
if (!token) {
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(loginUrl);
}
// Add user info to headers for downstream use
const response = NextResponse.next();
response.headers.set('x-user-token', token);
return response;
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};Sponsored
Clerk — Drop-in authentication for Next.js
Use Cases
- Dashboard access control
- SaaS route protection
- Redirect to login flow
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.