0
0
NextJSframework~3 mins

Why Protected routes with middleware in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could protect your whole site with just one simple check?

The Scenario

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.

The Problem

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.

The Solution

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.

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

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

This lets you protect many pages easily and keep your app safe without repeating code everywhere.

Real Life Example

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.

Key Takeaways

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.