# How to configure Next.js

&#x20;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.

```jsx
module.exports = {
  webpack: {
    // webpack config properties
    plugins: [new MyWebpackPlugin()],
  },
  env: {
    MY_ENV_VAR: process.env.SECRET,
  },
};
```

```jsx
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:

```jsx
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:

```jsx
// 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:

* [Use `.env.local` to load environment variables](https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables)
* [Expose environment variables to the browser](https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser)

&#x20;`.env.local` always overrides the defaults set.

{% hint style="warning" %}
`.env`, `.env.development`, `.env.production,` `.env.test` files should be included in your repository as they define defaults.&#x20;

`.env.local`,`.env.development.local`,`.env.test.local, .env.production.local` should be added to *.gitignore*, as those files are intended to be ignored.&#x20;

`.env.local` is where **secrets** can be stored.
{% endhint %}
