next.config.js: Your Next.js App's Control Panel
Think of `next.config.js` as your app's control panel, letting you change Next.js's default behavior. Use it for redirects, environment variables, or image optimization. The biggest footgun: you must restart your dev server after making any changes.
WHY IT EXISTS Next.js provides sensible defaults for a great developer experience, but real-world applications have unique requirements. You might need custom routing, specific build optimizations, or integration with existing infrastructure. The next.config.js file provides a centralized, official entry point to override these defaults without ejecting from the framework.
THE MENTAL MODEL Think of next.config.js as the main settings panel for your Next.js application. It's not a simple JSON file; it's a standard Node.js module. This means you can use JavaScript logic, import other modules, or read environment variables to dynamically create your configuration. The file's purpose is to export an object that tells Next.js how to behave.
HOW IT WORKS At the root of your project, you create a file named next.config.js. Inside, you define and export a configuration object using module.exports. For example, to enable React's Strict Mode, you would write module.exports = { reactStrictMode: true }. When you run next dev or next build, Next.js first reads this file, merges its contents with the default configuration, and then proceeds using the final, combined settings.
WHEN TO USE IT You'll edit this file for many common tasks. Three key examples are: first, setting up redirects or rewrites for SEO or URL restructuring; second, configuring the images property to allow remote image sources from a specific CDN; third, making environment variables available to the browser by adding them to the env object. It's also where you configure advanced features like custom Webpack settings or enabling experimental features like Turbopack.
WHEN NOT TO USE IT Do not put secrets or private API keys directly into next.config.js, especially in the env block. Anything in the env object is exposed to the client-side browser bundle. For server-side secrets, use standard environment variables (e.g., in .env.local) that are only accessible in server-side code. Also, avoid overly complex logic inside the config file; it can make your build process brittle and hard to debug.
ONE CANONICAL EXAMPLE A common scenario is redirecting an old path to a new one. In next.config.js, you would add a redirects function that returns an array of rules:
const nextConfig = { async redirects() { return [ { source: '/old-blog/:slug', destination: '/news/:slug', permanent: true, }, ] }, };
module.exports = nextConfig;
This tells Next.js to permanently redirect any request from /old-blog/some-post to /news/some-post.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.