Discover how one small piece of code can protect your entire API effortlessly!
Why Middleware for API routes in NextJS? - Purpose & Use Cases
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.