Discover how one small piece of code can protect your entire API effortlessly!
Why Middleware for API routes in NextJS? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have many API routes in your Next.js app, and you want to check if a user is logged in before they can access any of them.
You try to add the same login check code inside every single API route handler.
Manually repeating login checks in every API route is tiring and easy to forget.
If you miss one, unauthorized users might sneak in.
Also, updating the check means changing many files, which wastes time and causes bugs.
Middleware lets you write the login check once and apply it automatically to all or some API routes.
This keeps your code clean, safe, and easy to update.
export default function handler(req, res) {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
// rest of handler
}export function middleware(req) {
if (!req.headers.get('authorization')) {
return new Response('Unauthorized', { status: 401 });
}
return NextResponse.next();
}
import { NextResponse } from 'next/server';
export const config = { matcher: '/api/:path*' };You can protect many API routes with one simple middleware, making your app more secure and maintainable.
A shopping app uses middleware to check if users are logged in before allowing them to add items to their cart or place orders.
Manual checks in every API route cause repeated code and errors.
Middleware centralizes checks for cleaner, safer code.
It saves time and reduces bugs when updating security rules.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before the API route handler to process requests.Step 2: Identify correct purpose
It can check, block, or modify requests but does not replace handlers or style responses.Final Answer:
To run code before the API route handles a request -> Option AQuick Check:
Middleware runs before API handler [OK]
- Thinking middleware replaces the API handler
- Confusing middleware with styling or storage
- Assuming middleware runs after the API handler
Solution
Step 1: Recall Next.js middleware continuation method
To continue processing the request, middleware must call NextResponse.next().Step 2: Match correct method
NextResponse.stop() halts, redirect() sends elsewhere, error() signals failure.Final Answer:
return NextResponse.next() -> Option CQuick Check:
Use NextResponse.next() to continue [OK]
- Using NextResponse.stop() which blocks the request
- Confusing redirect() with continuing
- Forgetting to return NextResponse.next()
x-auth: secret is sent?
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.headers.get('x-auth') !== 'secret') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
}Solution
Step 1: Check header condition
The middleware checks if 'x-auth' header equals 'secret'. If yes, it continues.Step 2: Analyze given header
The request has 'x-auth: secret', so condition is false and middleware returns NextResponse.next().Final Answer:
The request continues to the API route handler -> Option BQuick Check:
Header matches 'secret' so continue [OK]
- Assuming redirect happens even if header matches
- Thinking middleware throws error on mismatch
- Ignoring header case sensitivity
import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.headers.get('authorization')) {
NextResponse.redirect('/login');
}
return NextResponse.next();
}Solution
Step 1: Check redirect usage
NextResponse.redirect must be returned to stop further processing.Step 2: Identify missing return
The code calls NextResponse.redirect but does not return it, so middleware continues incorrectly.Final Answer:
Missing return before NextResponse.redirect -> Option DQuick Check:
Always return redirect response [OK]
- Not returning redirect response
- Thinking middleware must be async
- Misplacing NextResponse.next() inside if block
token is missing or empty. Which code correctly implements this behavior?Solution
Step 1: Access query parameters correctly
Use new URL(request.url) and url.searchParams.get('token') to read query params.Step 2: Check token presence and redirect if missing
If token is missing or empty, redirect to /error; otherwise continue with NextResponse.next().Final Answer:
Code that checks query param and redirects if missing -> Option AQuick Check:
Use URL and searchParams for query checks [OK]
- Trying to access query params directly on request
- Checking headers instead of query parameters
- Reversing redirect and continue logic
