What if you could stop repeating the same security checks everywhere and handle them all in one place?
Why middleware intercepts requests in NextJS - The Real Reasons
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.
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.
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.
if (!userLoggedIn) { redirect('/login') } // repeated in every page
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('token')) { return NextResponse.redirect(new URL('/login', request.url)); } }
Middleware makes it easy to control access and modify requests globally, improving security and code clarity.
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.
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.