Protecting API Routes with Middleware

Jan 8, 2025

1 min read

Use middleware.ts in Next.js to protect routes via token-based auth:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value;

if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}

return NextResponse.next();
}

export const config = {
matcher: ['/dashboard/:path*'],
};

This enforces auth for all /dashboard routes.