Config-based, middleware, and in-render redirects.
Skip to solutionKEEP THE
mediumFrontend
How do you handle redirects and rewrites in Next.js?
813 views
01
Understand the problem
nextjsredirectsrewritesmiddleware
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Define static redirects()/rewrites() in next.config.js (redirect changes the URL; rewrite proxies internally while keeping the URL). For dynamic/conditional cases use middleware (NextResponse.redirect/rewrite) or call redirect() inside Server Components/Actions.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Config rules + conditional middleware
// next.config.js — static
async redirects() { return [{ source: '/blog/:slug', destination: '/posts/:slug', permanent: true }]; }
async rewrites() { return [{ source: '/api/:p*', destination: 'https://backend/:p*' }]; } // proxy
// middleware.ts — conditional
import { NextResponse } from 'next/server';
export function middleware(req) {
if (req.geo?.country === 'FR') return NextResponse.rewrite(new URL('/fr', req.url));
}05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 36 of 95 decoded in the Next.js track. One more won't hurt.