0
Can you explain how Middleware works in Next.js 13+ and give an example use case?
subina kallyani
hard
0completed
325
Answer
Middleware in Next.js runs before a request is completed and can modify the request/response. It executes on the Edge Runtime (faster and closer to the user).
Example use case: authentication (redirecting users if not logged in), logging, or A/B testing
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(req) {
const token = req.cookies.get('token');
if (!token) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0