Search code examples
javascriptreactjswebpacknext.js

Adding a webpack plugin inside a Next.js project


I'm trying to add the Webpack Bundle Analyzer to my Next.js app. I tried updating my next.config.js as follows:

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  plugins: [new BundleAnalyzerPlugin()],
};

module.exports = nextConfig;

But this throwing this error:

Invalid next.config.js options detected: The root value has an unexpected property, plugins, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

Solution

  • You are getting that error because you are not using the correct way to customize Webpack inside next.config.js. This is how you would do it:

    const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
    
    const nextConfig = {
      reactStrictMode: true,
      swcMinify: true,
      webpack: (config, { dev }) => {
        // The condition is to have the plugin on build time, not to perturb live refresh
        !dev && config.plugins.push(new BundleAnalyzerPlugin());
        return config;
      },
    };
    
    module.exports = nextConfig;
    

    For more, check out the doc at Custom Webpack Config.