Next.js
/Advanced
API Middleware Concepts
Definition
The architectural practice of intercepting API requests to perform tasks like authentication or rate limiting before the request reaches your specific Route Handler.
Explain Like I'm New
You have 50 API routes that require the user to be logged in. Instead of copy-pasting the exact same 'Check if user is logged in' code at the top of all 50 files, you put it in one global Middleware file. It checks the ID badge at the front door before letting them into the building.
Real World Example
Protecting the entire `/api/admin/*` path. If a user without an admin token tries to access it, the Middleware instantly bounces them with a 401 error before the Route Handler even wakes up.
Common Use Cases
- •Authentication
- •Rate Limiting
- •Bot detection
- •Logging
Interactive Example
// middleware.ts (At the root of the project!) import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // This function runs on EVERY request that matches the config below export function middleware(request: NextRequest) { // Check for an auth token const token = request.cookies.get('auth_token'); if (!token) { // Reject API requests instantly if (request.nextUrl.pathname.startsWith('/api/')) { return NextResponse.json({ error: 'Auth required' }, { status: 401 }); } // Redirect webpage requests to login return NextResponse.redirect(new URL('/login', request.url)); } // Allow the request to continue normally return NextResponse.next(); } // Tell Middleware to ONLY run on API routes and the Dashboard export const config = { matcher: ['/api/:path*', '/dashboard/:path*'], };
Interview Questions
basic
- Where must the `middleware.ts` file be located in a Next.js project?
intermediate
- How do you prevent the Middleware from running on static assets like images and CSS files?