Custom Webpack Config

Note: changes to webpack config are not covered by semver so proceed at your own risk

Before continuing to add custom webpack configuration to your application make sure Next.js doesn’t already support your use-case:

Some commonly asked for features are available as plugins:

In order to extend our usage of webpack, you can define a function that extends its config inside next.config.js, like so:

  1. module.exports = {
  2. webpack: (
  3. config,
  4. { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
  5. ) => {
  6. // Important: return the modified config
  7. return config
  8. },
  9. }

The webpack function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using the isServer property.

The second argument to the webpack function is an object with the following properties:

  • buildId: String - The build id, used as a unique identifier between builds
  • dev: Boolean - Indicates if the compilation will be done in development
  • isServer: Boolean - It’s true for server-side compilation, and false for client-side compilation
  • nextRuntime: String | undefined - The target runtime for server-side compilation; either "edge" or "nodejs", it’s undefined for client-side compilation.
  • defaultLoaders: Object - Default loaders used internally by Next.js:
    • babel: Object - Default babel-loader configuration

Example usage of defaultLoaders.babel:

  1. // Example config for adding a loader that depends on babel-loader
  2. // This source was taken from the @next/mdx plugin source:
  3. // https://github.com/vercel/next.js/tree/canary/packages/next-mdx
  4. module.exports = {
  5. webpack: (config, options) => {
  6. config.module.rules.push({
  7. test: /\.mdx/,
  8. use: [
  9. options.defaultLoaders.babel,
  10. {
  11. loader: '@mdx-js/loader',
  12. options: pluginOptions.options,
  13. },
  14. ],
  15. })
  16. return config
  17. },
  18. }

nextRuntime

Notice that isServer is true when nextRuntime is "edge" or "nodejs", nextRuntime “edge“ is currently for middleware and server components in edge runtime only.

Introduction to next.config.jsLearn more about the configuration file used by Next.js.