typescriptnext.jswebpacknextjs14server-action

How to opt out specific packages of bundling


I want to opt specific packages out of bundling. The documentation says:

/** @type {import('next').NextConfig} */
const nextConfig = {
  serverExternalPackages: ['package-name'],
}
 
module.exports = nextConfig

but the compiler says otherwise:

⚠ Invalid next.config.mjs options detected: 
⚠     Unrecognized key(s) in object: 'serverExternalPackages'
⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config

I did try this, of course:

/** @type {import('next').NextConfig} */
const nextConfig = {
  serverExternalPackages: ['package-name'],
}
 
module.exports = nextConfig

but the compiler immediately throws an error.


Solution

  • Even the solution I tried previously was in the Nextjs documentation. Looks like serverExternalPackages is no longer a valid option for the Nextjs configuration.

    To exclude certain packages from being bundle on the server-side, Nextjs provide the following way to handle package exclusions: Offloading the task to webpack!

    /** @type {import('next').NextConfig} */
    const nextConfig = {
        webpack: (config, { isServer }) => {
            if (isServer) {
                // Exclude packages from the server-side bundle
                config.externals.push('muhammara', '@mapbox/node-pre-gyp');
            }
            return config;
        },
    }
    
    export default nextConfig;