0
0
NextJSframework~3 mins

Why Middleware for API routes in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one small piece of code can protect your entire API effortlessly!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
export default function handler(req, res) {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  // rest of handler
}
After
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*' };
What It Enables

You can protect many API routes with one simple middleware, making your app more secure and maintainable.

Real Life Example

A shopping app uses middleware to check if users are logged in before allowing them to add items to their cart or place orders.

Key Takeaways

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.