Topic 44 of 47
Middleware Edge
Overview
Middleware allows you to run code before a request is completed. Because it runs on the Edge Runtime (not Node.js), it is incredibly fast and executes globally before routing, making it ideal for Authentication, Redirects, and Bot Protection.
Syntax
typescript
// middleware.ts (Must be placed in the project root, outside the app/ directory)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth-token');
// If trying to access /dashboard without a token, redirect to login
if (request.nextUrl.pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Otherwise, continue to the requested page
return NextResponse.next();
}
// Optional: Configure which paths trigger the middleware
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*'],
};Common Pitfalls
- Middleware runs on the Edge Runtime. You CANNOT use Node.js specific APIs like `fs` (file system), `crypto` module, or connect directly to standard databases.
- If you do not define a `matcher` in the config, the middleware will run on EVERY single request, including static assets and images, which can hurt performance.
Real-World Example
Rewriting URLs for A/B testing or localization:
example
typescript
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const url = request.nextUrl.clone();
// A/B Testing: randomly assign users to the new homepage
if (url.pathname === '/') {
const bucket = request.cookies.get('bucket')?.value || (Math.random() > 0.5 ? 'new' : 'old');
if (bucket === 'new') {
url.pathname = '/home-v2';
} else {
url.pathname = '/home-v1';
}
const response = NextResponse.rewrite(url);
response.cookies.set('bucket', bucket);
return response;
}
}