Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 72 ยท Configuration, Tooling and Testing

Configuring Next.js

A tour of next.config.ts: typed config, redirects versus rewrites, custom headers, env, image settings, output modes, and the experimental flags to treat with care.

Most Next.js apps run on defaults for a long time, and then one day you need to move a URL, add a security header, allow images from another domain or build a Docker-friendly output. All of that lives in one file at the root of the project: next.config.ts. It is read once when the server starts, runs on Node.js (never in the browser), and returns an object of options.

This lesson tours the options you will use most. You will learn the difference between a redirect and a rewrite, which people mix up constantly, see how custom headers are matched, and get a map of the other common settings and the risky experimental area. Next.js configuration cannot run on this site, so every config sample is read-only. Two Node stand-ins run the matching logic so you can try the redirect, rewrite and header rules on sample URLs.

One file, many knobs

redirects Send the browser to a new URL.
rewrites Serve one path from another, URL unchanged.
headers Add response headers to matching paths.
images Allowed hosts and formats for next/image.
1 / 2

The config file

Next.js looks for next.config.ts, next.config.mjs, next.config.js or next.config.cjs. The TypeScript version gives you autocomplete and type checking through the NextConfig type:

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  reactStrictMode: true,
  poweredByHeader: false,
};

export default nextConfig;

Two properties to remember. First, the file runs at startup, so changes need a restart of next dev. Second, it runs in Node.js, so you may read process.env, import node:path or call fs, but anything you put in it never reaches the browser unless an option explicitly says so. The default export can also be an async function that receives the current phase (such as development server or production build) and returns the object, which lets you vary settings per phase.

The two most common small options are reactStrictMode (extra development checks such as double-rendering effects; the App Router enables it by default) and poweredByHeader: false, which removes the X-Powered-By: Next.js response header.

Redirects

A redirect tells the browser to go somewhere else. The server answers with a status code and a Location header, and the address bar changes. Use redirects when a page has moved for good, when you rename a section, or when you merge duplicate URLs, because search engines then transfer the old address's ranking to the new one.

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async redirects() {
    return [
      {
        source: "/old-blog/:slug",
        destination: "/blog/:slug",
        permanent: true, // status 308
      },
      {
        source: "/docs/:path*",
        destination: "/learn/:path*",
        permanent: false, // status 307
      },
    ];
  },
};

export default nextConfig;

Each rule has a source pattern, a destination, and permanent. A permanent redirect returns status 308 and browsers and crawlers cache it aggressively; a temporary one returns 307. Pick permanent: true only when you are sure, since a cached wrong redirect is hard to undo.

The path patterns use a small syntax:

  • :slug matches exactly one path segment.
  • :path* matches zero or more segments.
  • :path+ matches one or more segments.
  • A parenthesized regular expression restricts a match, such as :id(\\d+) for digits only.
  • A rule can also have has or missing conditions on headers, cookies or query values, so you can redirect only visitors with a certain cookie, for example.

Redirects in the config are static. For decisions that depend on the user or on data, use redirect() inside a Server Component or action, or the proxy file (Middleware and the Proxy File).

Rewrites

A rewrite maps an incoming path to a different destination without changing the URL in the browser. The visitor keeps seeing /shop/42 while the app renders /products/42. Rewrites are useful for friendly URLs, for gradually migrating a site, and for proxying part of your site to another service.

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async rewrites() {
    return [
      { source: "/shop/:id", destination: "/products/:id" },
      { source: "/api-docs/:path*", destination: "https://docs.example.com/:path*" },
    ];
  },
};

export default nextConfig;

The second rule proxies to an external host, so the visitor reads another service's pages under your domain. Bear in mind that your server then pays for those requests.

rewrites() may also return an object with three lists: beforeFiles, afterFiles and fallback. They differ in when they are checked. The overall order of a request is: headers, redirects, the proxy file, beforeFiles rewrites, files and routes from your app (including public/), afterFiles rewrites, dynamic routes, and finally fallback rewrites. A plain array is the same as afterFiles, which means real pages win over a rewrite. That is the safe default for gradual migrations: the new app handles what it has, and everything else falls through to the old site.

The stand-in below applies redirects first and rewrites second, the same order Next.js uses, so you can try several URLs. It converts the patterns to regular expressions in a simplified way; the real framework uses a full path-matching library.

Node.js Redirects first, then rewrites

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare the lines: the two redirects say "go there" and change the address; the two rewrites serve content from elsewhere and leave the address alone; /about matches nothing and goes to the normal routes. Because redirects are checked before rewrites, a URL matched by both is redirected.

Custom headers

headers() adds response headers to paths that match a source. It is how most apps set security headers and cache rules that apply to many pages.

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async headers() {
    return [
      {
        source: "/:path*",
        headers: [
          { key: "X-Content-Type-Options", value: "nosniff" },
          { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
          { key: "X-Frame-Options", value: "DENY" },
        ],
      },
      {
        source: "/account/:path*",
        headers: [{ key: "Cache-Control", value: "private, no-store" }],
      },
    ];
  },
};

export default nextConfig;

When several rules match one URL, all of their headers are added, and if two rules set the same header key the later rule wins. The stand-in below shows that merge on a few paths.

Node.js Which headers does a path get?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Public pages get the one-hour cache header, while everything under /account is overridden with private, no-store, which is the rule you want for personal data (see Cookies and Headers). A header like Content-Security-Policy that needs a fresh random value per request cannot be written statically here; set it in the proxy file instead.

Environment variables in the config

The env option inlines values into the JavaScript bundle at build time:

TypeScript
// read-only
const nextConfig: NextConfig = {
  env: { APP_VERSION: process.env.npm_package_version },
};

Anything in env is public, since it is replaced in client code at build time. For most needs, .env files and NEXT_PUBLIC_ variables are the better tool, and Environment Variables and Secrets covers them. Never put a secret in this option.

Images

next/image only optimizes images from hosts you list. This is a safety feature: without it, anyone could use your server to resize arbitrary pictures.

TypeScript
// next.config.ts (read-only)
const nextConfig: NextConfig = {
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "images.example.com", pathname: "/photos/**" },
    ],
    formats: ["image/avif", "image/webp"],
  },
};

Make the pathname as narrow as you can. Sizes, quality and caching settings live here too; the component side is described in Image Optimization with next/image.

Output modes and paths

The output option changes what next build produces:

  • Unset (the default) builds a normal server app. You run it with next start.
  • "standalone" builds a minimal self-contained server with only the needed files, ideal for Docker.
  • "export" builds plain static HTML, CSS and JavaScript into an out folder that any static host can serve. It supports only features that need no server, so there are no Server Actions, route handlers that read the request, or proxy.

basePath: "/docs" serves the whole app under a sub-path, trailingSlash: true makes URLs end in /, and assetPrefix points static files to a CDN. Set basePath at build time; it cannot change after the build. Deployment choices are covered in Building and Deploying.

A map of other common options

  • typedRoutes: true makes Link and router.push check that a path exists.
  • reactCompiler: true enables the React Compiler for automatic memoization (see Bundle Size and Core Web Vitals).
  • cacheComponents: true opts into the use cache model from The use cache Directive and Cache Components.
  • serverExternalPackages lists packages that should be loaded by Node.js at run time and not bundled, which some native or large packages need.
  • transpilePackages asks Next.js to compile source code in a dependency, typically a monorepo package.
  • turbopack holds settings for the Turbopack bundler, such as extra loader rules.
  • redirects, rewrites and headers can also be inspected in the build output.

The experimental area

The experimental object holds features that are still being tested. They can change behavior, be renamed or disappear in a minor release, and some are promoted to stable top-level options in later versions (several of the options above started life there). Rules for living with them: enable a flag only when you need what it does, read the release notes when you upgrade, keep a list of the flags you use and the reason, and never copy a long experimental block from a blog post written for another version. See Upgrading and Migrating from Pages Router for upgrade habits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between a redirect and a rewrite?

    A redirect sends the browser to a new URL. A rewrite maps the request internally to another destination and the visitor's URL stays the same.
  2. 2. You moved a page permanently and want search engines to transfer its ranking. Which setting is right?

    A permanent redirect tells browsers and search engines that the old URL has been replaced by the new one.
  3. 3. Two header rules match a path and both set Cache-Control. Which value is sent?

    When several rules set the same header key for one path, the last matching rule overrides the earlier ones.
  4. 4. Which output setting creates a minimal self-contained server that suits Docker?

    standalone copies only the files the server needs. export creates static files only and has no server.
  5. 5. Why should you not put a secret in the env option of next.config.ts?

    Values in env are replaced in the JavaScript sent to the browser, so they are public.

Summary

  • next.config.ts runs once in Node.js at startup and exports a typed NextConfig object; restart the dev server after changes.
  • Redirects change the URL (307 temporary, 308 permanent); rewrites serve other content under the same URL; the order is headers, redirects, proxy, beforeFiles, routes, afterFiles, dynamic routes, fallback.
  • headers() adds response headers by path; later rules override earlier ones for the same key.
  • images.remotePatterns lists allowed image hosts; keep patterns narrow.
  • output selects the build type: default server, standalone for self-hosting, export for static files.
  • Treat experimental flags as temporary, document why you use each, and recheck them on every upgrade.

Next: Environment Variables and Secrets