0
0
NextjsHow-ToBeginner · 4 min read

How to Configure next.config.js in Next.js for Custom Settings

To configure Next.js, create a next.config.js file in your project root exporting an object with settings. This file lets you customize features like environment variables, image optimization, and webpack behavior.
📐

Syntax

The next.config.js file must export a JavaScript object with configuration options. Each key in this object controls a specific Next.js feature or behavior.

Example keys include reactStrictMode, env, images, and webpack. You can also export a function to customize webpack.

javascript
module.exports = {
  reactStrictMode: true,
  env: {
    CUSTOM_KEY: 'value'
  },
  images: {
    domains: ['example.com']
  },
  webpack(config, options) {
    // customize webpack config here
    return config
  }
}
💻

Example

This example shows a next.config.js that enables React strict mode, sets an environment variable, allows images from a domain, and customizes webpack to add a plugin.

javascript
const webpack = require('webpack')

module.exports = {
  reactStrictMode: true,
  env: {
    API_URL: 'https://api.example.com'
  },
  images: {
    domains: ['images.example.com']
  },
  webpack(config) {
    config.plugins.push(new webpack.DefinePlugin({
      'process.env.VERSION': JSON.stringify('1.0.0')
    }))
    return config
  }
}
Output
Next.js builds with React strict mode enabled, environment variable API_URL accessible in code, images allowed from images.example.com, and process.env.VERSION set to '1.0.0'.
⚠️

Common Pitfalls

  • Forgetting to export the config object with module.exports causes Next.js to ignore the file.
  • Using ES module syntax (export default) in next.config.js is not supported; use CommonJS module.exports.
  • Modifying the webpack config incorrectly can break the build; always return the modified config.
  • Environment variables set in env are embedded at build time and cannot be changed at runtime.
javascript
/* Wrong way: Using ES module export */
export default {
  reactStrictMode: true
}

/* Right way: Using CommonJS export */
module.exports = {
  reactStrictMode: true
}
📊

Quick Reference

OptionDescriptionExample Value
reactStrictModeEnables React strict mode for highlighting potential problemstrue
envDefines environment variables accessible in code{ API_URL: 'https://api.example.com' }
images.domainsAllows external image domains for next/image optimization['images.example.com']
webpackFunction to customize webpack config(config) => { return config }

Key Takeaways

Create next.config.js in your project root exporting a config object with module.exports.
Use CommonJS syntax; do not use ES module exports in next.config.js.
Configure features like reactStrictMode, env variables, images, and webpack inside this file.
Always return the modified webpack config if you customize it.
Environment variables in next.config.js are embedded at build time, not runtime.