0
0
NextJSframework~3 mins

Why middleware intercepts requests in NextJS - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could stop repeating the same security checks everywhere and handle them all in one place?

The Scenario

Imagine you have a website where users must log in to see certain pages. Without middleware, you have to check the login status on every page manually, repeating the same code everywhere.

The Problem

Manually adding login checks on every page is slow, error-prone, and easy to forget. If you miss one page, unauthorized users might see private info. It also makes your code messy and hard to maintain.

The Solution

Middleware intercepts requests before they reach your pages. It lets you run code once to check login status, redirect users, or modify requests, keeping your app secure and clean.

Before vs After
Before
if (!userLoggedIn) { redirect('/login') } // repeated in every page
After
import { NextResponse } from 'next/server';

export function middleware(request) {
  if (!request.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
What It Enables

Middleware makes it easy to control access and modify requests globally, improving security and code clarity.

Real Life Example

Think of middleware like a security guard at a building entrance who checks everyone before they enter, so you don't have to check inside every room.

Key Takeaways

Manual checks on every page are repetitive and risky.

Middleware runs once per request to handle common tasks.

This keeps your app secure, clean, and easier to maintain.