Next.js
/Beginner
Middleware Fundamentals
Definition
Code that executes BEFORE a request is completed. It allows you to intercept incoming HTTP requests, run logic, and modify the response.
Explain Like I'm New
Imagine a bouncer at a club. Before you get inside the building (the App router), the bouncer (Middleware) stops you, checks your ID, and decides whether to let you in, kick you out, or redirect you to a different door.
Real World Example
Checking if a user is logged in. If they aren't, the Middleware intercepts their request for `/dashboard` and forcefully redirects them to `/login`.
Common Use Cases
- •Authentication
- •A/B Testing
- •Internationalization (i18n) routing
- •Bot protection
Interactive Example
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { // 1. Intercept the request console.log(`Someone is trying to visit: ${request.nextUrl.pathname}`); // 2. Perform logic if (request.nextUrl.pathname === '/secret') { // 3. Modify the response (Redirect them away!) return NextResponse.redirect(new URL('/', request.url)); } // 4. Let them through normally return NextResponse.next(); }
Interview Questions
basic
- Does Middleware run on the Server or the Client browser?
intermediate
- If you have 10,000 pages on your site, does the Middleware run 10,000 times?