0
0
NextJSframework~3 mins

Why Redirect and rewrite in middleware in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one simple middleware can save you hours of repetitive redirect headaches!

The Scenario

Imagine you have a website where users need to be sent to different pages based on their location or login status. You try to handle this by checking every page manually and writing code in each page to redirect users.

The Problem

This manual approach is slow and messy. You have to repeat the same redirect logic on many pages, making your code hard to maintain. If you forget to add the redirect on one page, users might see wrong content or errors.

The Solution

Using middleware for redirects and rewrites lets you handle these rules in one place. Middleware runs before your pages load, so you can send users to the right page automatically without repeating code everywhere.

Before vs After
Before
if (!userLoggedIn) { window.location.href = '/login'; }
After
import { NextResponse } from 'next/server';

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

This lets you control user flow smoothly and securely, improving user experience and keeping your code clean and easy to update.

Real Life Example

For example, an online store can redirect users from a general homepage to a country-specific page automatically, or send users to login if they try to access their account without signing in.

Key Takeaways

Manual redirects on every page cause repeated code and errors.

Middleware centralizes redirect and rewrite logic before pages load.

This improves site speed, security, and maintainability.