What if you could protect your whole site with just one simple check?
Why Protected routes with middleware in NextJS? - Purpose & Use Cases
Imagine you have a website where some pages should only be seen by logged-in users. You try to check if a user is logged in on every page manually by adding code everywhere.
Manually checking login status on every page is tiring and easy to forget. If you miss one page, anyone can see it. It also makes your code messy and hard to update.
Using middleware for protected routes lets you write the login check once. Middleware runs before your pages load and blocks access if the user is not logged in, keeping your code clean and secure.
if (!user) { redirect('/login') } // on every page
import { NextResponse } from 'next/server'; export function middleware(req) { if (!req.cookies.get('token')) { return NextResponse.redirect(new URL('/login', req.url)); } }
This lets you protect many pages easily and keep your app safe without repeating code everywhere.
Think of a gym where only members can enter certain rooms. Middleware is like a guard checking membership at the door, so you don't need a guard inside every room.
Manual checks on every page are slow and error-prone.
Middleware runs once before pages load to protect routes.
This keeps your app secure and your code simple.