MiddlewareIntermediate
1Question 1 of 1
typescriptHow does Middleware work in Next.js and when should you use it?
Explanation & Concept
Next.js Middleware (`middleware.ts`) runs before a request is completed. It executes on the lightweight Edge Runtime, allowing request interception, header modification, rewriting, redirects, and session validation before pages render.
Code Example
typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("authToken")?.value;
// Protect all /admin routes
if (request.nextUrl.pathname.startsWith("/admin") && !token) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*"]
};How It Works & Key Takeaways
Middleware rejects unauthenticated requests at the Edge before rendering or running database queries, enhancing performance and security.
Mock Test · 1 Questions · Optional
Ready for Dynamic Routing?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions