This error occurs because webpack is trying to resolve the Node.js built-in modules in the browser context. We need to provide polyfills or fallbacks for these modules. For your case, you'll need to use the node-polyfills-webpack-plugin or manually configure the fallbacks.
Here's how to modify your webpack config:
const NodePolyfillPlugin = require('node-polyfills-webpack-plugin');
const NodePrefixStripPlugin = require('./node-prefix-strip-plugin');
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
// Browser-side specific configs
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
net: require.resolve('net-browserify'),
tls: require.resolve('tls-browserify'),
dns: require.resolve('dns-browserify'),
async_hooks: false,
path: require.resolve('path-browserify'),
};
// Add the polyfill plugin
config.plugins.push(new NodePolyfillPlugin());
}
config.plugins.push(new NodePrefixStripPlugin());
return config;
},
};
module.exports = nextConfig;
First, install the required dependencies:
npm install --save-dev node-polyfills-webpack-plugin net-browserify tls-browserify dns-browserify path-browserify
This setup will:
- Provide browser-compatible versions of Node.js built-in modules where possible
- Set modules that can't be polyfilled to
false
- Use the NodePolyfillPlugin to handle other Node.js core modules
If you specifically don't want to use these modules in the browser and just want to mock them out completely, you could create an empty mock file (like you did with dd-trace) and use it for all Node.js built-ins:
const path = require('path');
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
net: false,
tls: false,
dns: false,
async_hooks: false,
path: false,
};
// Replace all Node.js built-ins with empty mock
config.plugins.push(
new webpack.NormalModuleReplacementPlugin(
/^(net|tls|dns)$/,
path.resolve(__dirname, 'mocks/empty.js')
)
);
}
config.plugins.push(new NodePrefixStripPlugin());
return config;
},
};
module.exports = nextConfig;
Choose the approach that best fits your needs:
- Use polyfills if you need the functionality to work in the browser
- Use empty mocks if you just need the code to compile but don't need the actual functionality
- Or use a combination of both depending on which modules you actually need