Next.jsEasy
How do you redirect users in middleware?
Return NextResponse.redirect(url) from proxy.ts with an absolute URL, usually built from the request: new URL("/login", request.url). It defaults to a 307 temporary redirect; pass 308 (or 301) as the second argument for permanent ones.
Building the target
new URL("/login", request.url)keeps the host and protocol.- Clone
request.nextUrlto change only the path or query:const url = request.nextUrl.clone(); url.pathname = "/login". - Preserve where the user was going:
url.searchParams.set("next", request.nextUrl.pathname).
Status codes
- 307 (default): temporary, method preserved.
- 308: permanent, method preserved. Good for moved pages.
- 301/302 work too, but they may change POST to GET.
Avoid redirect loops
Do not redirect a path to itself: exclude /login from the auth check, or use the matcher to skip it.
Choosing where to redirect
- Static mappings (old URL to new URL):
redirects()innext.config.ts. It runs before Proxy and needs no code. - Thousands of redirects from a CMS: store them in a fast lookup (Edge Config, Redis, a Bloom filter) and check them in Proxy.
- Logic-based: auth, locale, geo, feature flags belong in Proxy.
- After a mutation or during render:
redirect()in Server Functions and Server Components.
Code example
tsx
1// proxy.ts2import { NextResponse, type NextRequest } from "next/server";34const PROTECTED = ["/dashboard", "/settings"];56export function proxy(request: NextRequest) {7 const { pathname } = request.nextUrl;8 const loggedIn = request.cookies.has("session");910 // Temporary redirect to login, remembering the destination11 if (!loggedIn && PROTECTED.some((p) => pathname.startsWith(p))) {12 const url = request.nextUrl.clone();13 url.pathname = "/login";14 url.searchParams.set("next", pathname);15 return NextResponse.redirect(url); // 30716 }1718 // Logged-in users should not see the login page19 if (loggedIn && pathname === "/login") {20 return NextResponse.redirect(new URL("/dashboard", request.url));21 }2223 // Permanent move24 if (pathname.startsWith("/docs/v1")) {25 return NextResponse.redirect(new URL(pathname.replace("/docs/v1", "/docs"), request.url), 308);26 }27}2829export const config = { matcher: ["/dashboard/:path*", "/settings/:path*", "/login", "/docs/v1/:path*"] };
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.