How to configure Next.js

Next.js is production-ready and handles almost everything, but don't be scared to reach to that config and extend what you need.

If you want to change the build system's behavior, extend Next.js' s features, or add ENV variables, you can do this in the next-config.js file.

module.exports = {
  webpack: {
    // webpack config properties
    plugins: [new MyWebpackPlugin()],
  },
  env: {
    MY_ENV_VAR: process.env.SECRET,
  },
};
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    console.log("I'm in dev mode");
  }
  return defaultConfig;
};

Bundle analyzer webpack plugin during a prod build of Next.js:

const { PHASE_PRODUCTION_SERVER } = require("next/constants");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    return {
      ...defaultConfig,
      webpack: {
        plugins: [new BundleAnalyzerPlugin()],
      },
    };
  }

  return defaultConfig;
};

Phases of Next.js:

  • PHASE_EXPORT

  • PHASE_PRODUCTION_BUILD

  • PHASE_PRODUCTION_SERVER // live, running on the server

  • PHASE_DEVELOPMENT_SERVER

Most plugins follow the withPluginName format. They also usually take your custom Next.js config, if any, to ensure it's returned and consumed by Next.js. This allows you to compose plugins:

// next.config.js
const withPlugins = require('next-compose-plugins')
const withOffline = require('next-offline')
const withReactSvg = require('next-react-svg')
const config = {
  env: {
    MY_ENV: process.env.MY_ENV
  }
}

module.exports = withPlugins([
  withOffline,
  [withReactSvg, {
    // config for reactSvgPlugin
  }]
], config)

Next.js comes with built-in support for environment variables, which allows you to do the following:

.env.local always overrides the defaults set.

.env, .env.development, .env.production, .env.test files should be included in your repository as they define defaults.

.env.local,.env.development.local,.env.test.local, .env.production.local should be added to .gitignore, as those files are intended to be ignored.

.env.local is where secrets can be stored.

Last updated