typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
#nextjs#middleware
typescriptadvanced
Middleware Chain Pattern
Compose multiple middleware functions for auth, rate limiting, and geolocation in Next.js middleware.
Best for: Auth guard middleware
#nextjs#middleware
typescriptadvanced
Middleware Geo-based Redirect
Redirect users based on their geographic location using Next.js edge middleware.
Best for: internationalization
#nextjs#middleware
typescriptintermediate
Cookies and Headers in Server Components
Read and set cookies and headers in Next.js server components and route handlers.
Best for: theme preferences
#nextjs#cookies