Discover how one simple middleware can save you hours of repetitive redirect headaches!
Why Redirect and rewrite in middleware in NextJS? - Purpose & Use Cases
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.
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.
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.
if (!userLoggedIn) { window.location.href = '/login'; }
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('user')) { return NextResponse.redirect(new URL('/login', request.url)); } }
This lets you control user flow smoothly and securely, improving user experience and keeping your code clean and easy to update.
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.
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.