Redirects & Rewrites Configuration

5 questions found

How do you set up a permanent redirect from an old URL to a new one in Next.js?

Beginner
You add a redirects function inside your next.config.js file, returning an array of redirect rules that each specify a source path, a destination path, and whether it should be a permanent redirect, which Next.js applies automatically without needing any additional code.
// next.config.js
module.exports = {
  async redirects() {
    return [
      { source: '/old-blog', destination: '/blog', permanent: true }
    ];
  }
};
Real-world example A company redesigns its website and adds a permanent redirect from its old blog URL to the new one, preserving search engine rankings that had built up over years at the old address.

Common follow-ups: What is the difference between a permanent and a temporary redirect?;Do redirects configured in next.config.js apply during development as well as production?

Metadata API & SEO Optimization;Next.js Project Setup & Configuration

What is a rewrite in Next.js, and how is it different from a redirect?

Beginner
A rewrite serves content from a different internal path while keeping the original URL visible in the browser's address bar, unlike a redirect which actually changes the URL the visitor sees, making rewrites useful for things like proxying requests to another service without exposing that underlying path.
// next.config.js
module.exports = {
  async rewrites() {
    return [
      { source: '/api/proxy/:path*', destination: 'https://external-api.example.com/:path*' }
    ];
  }
};
Real-world example A company proxies requests to an external analytics service through their own domain using a rewrite, keeping the external service's actual address hidden from visitors browsing their site.

Common follow-ups: Can rewrites point to an entirely external URL outside your own domain?;Do search engines see the original URL or the rewritten destination?

Middleware;Security Best Practices in Next.js

How do you use dynamic parameters within a redirect or rewrite rule to handle a whole pattern of URLs at once?

Intermediate
You use a named parameter with a colon inside your source path, such as :slug, and reference that same parameter name inside your destination path, letting a single rule handle many different specific URLs that all share the same overall pattern.
// next.config.js
module.exports = {
  async redirects() {
    return [
      { source: '/blog/:slug', destination: '/articles/:slug', permanent: true }
    ];
  }
};
Real-world example A publishing company renames its blog section to articles and sets up a single redirect rule using a dynamic slug parameter, automatically redirecting every existing blog post URL to its new equivalent address.

Common follow-ups: Can you combine multiple dynamic parameters in a single redirect rule?;What happens if a requested path does not match the expected parameter pattern?

Dynamic Routes & Catch-All Segments;Metadata API & SEO Optimization

How would you conditionally redirect users based on something dynamic, like whether they are logged in, rather than a fixed rule in next.config.js?

Intermediate
Since the redirects function in next.config.js only supports static, build time rules, you use middleware instead for conditional redirects that depend on runtime information like cookies or headers, checking the condition and returning a redirect response only when it applies.
// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const isLoggedIn = request.cookies.has('session');
  if (!isLoggedIn && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
Real-world example An application redirects visitors trying to access the dashboard to the login page only if they do not have a valid session cookie, a decision that can only be made at request time using middleware.

Common follow-ups: Why can't this kind of conditional logic be handled in the static redirects configuration?;How do you avoid redirect loops when combining middleware with static redirects?

Middleware;Authentication & Authorization in Next.js

What are best practices for managing a large number of redirects on a website that has gone through multiple redesigns over the years?

Advanced
Keep your redirect rules organized in a clearly documented list, regularly audit and remove ones that are no longer needed, avoid chaining multiple redirects together since each hop adds delay, and consider storing very large redirect lists in a database or external service rather than directly inside your configuration file if the list grows into the thousands.
// Avoid chains: redirect directly to the final destination
// Bad: /old -> /middle -> /new
// Good: /old -> /new
module.exports = {
  async redirects() {
    return [{ source: '/old', destination: '/new', permanent: true }];
  }
};
Real-world example A company that has redesigned its website three times over the years audits its growing list of redirects, removing outdated chains and consolidating them into direct redirects to improve page load speed.

Common follow-ups: How many redirect hops is considered too many for performance and SEO?;When should redirects be moved out of next.config.js and into a database instead?

Web Vitals & Performance Monitoring;Metadata API & SEO Optimization