Next.jsEasy
How does Next.js handle redirects in next.config.js?
Define an async redirects() function in next.config.ts that returns an array of { source, destination, permanent } rules. They run before Proxy and before routing, support path parameters, wildcards and regex, and can match on headers, cookies, query or host with has and missing.
Rule fields
source: incoming path pattern, for example/blog/:slugor/docs/:path*.destination: target path or absolute URL, reusing params (/news/:slug).permanent:truesends 308,falsesends 307. These preserve the HTTP method (unlike 301/302).statusCode: set an explicit code instead ofpermanent(rarely needed).basePath: false,locale: falsefor apps using those features.has/missing: conditions onheader,cookie,queryorhost.
Matching details
:parammatches one segment,:path*zero or more,:path+one or more.- Regex:
/post/:id(\\d{1,}). - Query strings are passed through to the destination automatically.
When to use something else
- Logic or lookups (auth, geo, A/B, CMS-driven redirects): Proxy.
- Thousands of redirects: keep them out of config (it slows startup and has platform limits); store them in a data source and check in Proxy.
- Redirect after a mutation or during render:
redirect()fromnext/navigation.
Order
Config headers run first, then config redirects, then Proxy.
Code example
tsx
1// next.config.ts2import type { NextConfig } from "next";34const nextConfig: NextConfig = {5 async redirects() {6 return [7 // Simple permanent move (308)8 { source: "/about-us", destination: "/about", permanent: true },9 // Params and wildcards10 { source: "/blog/:slug", destination: "/news/:slug", permanent: true },11 { source: "/docs/v1/:path*", destination: "/docs/:path*", permanent: false }, // 30712 // Regex on params13 { source: "/post/:id(\\d{1,})", destination: "/articles/:id", permanent: true },14 // Conditional: only when a cookie is missing15 {16 source: "/dashboard/:path*",17 missing: [{ type: "cookie", key: "session" }],18 destination: "/login",19 permanent: false,20 },21 // Host-based redirect to the canonical domain22 { source: "/:path*", has: [{ type: "host", value: "www.acme.com" }], destination: "https://acme.com/:path*", permanent: true },23 ];24 },25};2627export default nextConfig;
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.