typescriptintermediate

Authentication Middleware Guard

Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.

typescript
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.