How to Fix: Module not found: Can’t resolve ‘_http_common’

6 min read

Encountering "Module not found: Can’t resolve ‘_http_common’" can be a frustrating roadblock in modern web development, especially when working with tools like MSW (Mock Service Worker) or other libraries that bridge server-side and client-side environments. This error typically signifies that your client-side bundle is attempting to import an internal Node.js module, a common misconfiguration that prevents your application from building or running correctly in the browser.

Understanding the Root Cause

The core of the problem lies in the nature of _http_common. It is a private, internal module within Node.js, not designed for direct consumption or intended for client-side browser environments. When your bundler (like Vite, Webpack, or Rollup) encounters this error during a client-side build, it means that a part of your application or one of its dependencies is attempting to import or utilize this Node.js internal module.

Specifically, this often happens when:

  • A library aims to be "universal" (working in both Node.js and browser environments) but its browser build incorrectly includes Node.js-specific imports.
  • Node.js built-in modules (e.g., http, url, stream) are referenced using the node: prefix (e.g., node:url, node:http), which became standard in Node.js 16.x. Modern bundlers, by default, might not know how to resolve these in a browser context. The _http_common module is an internal dependency of these higher-level Node.js modules.
  • In the context of MSW, while MSW itself is designed for both environments, its underlying implementation or certain configurations might implicitly pull in Node.js internals if the bundler isn’t properly configured to provide browser-compatible shims or polyfills. This is not typically an MSW bug, but rather a configuration challenge related to how your build tool processes Node.js module imports for the browser.

Essentially, your browser-targeted build environment is missing the necessary polyfills or shims that tell it how to handle Node.js-specific code gracefully.

Step-by-Step Solution

The most robust solution involves configuring your bundler to correctly handle Node.js built-in modules in a browser environment. We’ll primarily focus on Vite, as it’s a common bundler where this issue arises, often with the node: prefix imports.

For Vite Projects

The recommended approach for Vite is to use a plugin that automatically provides browser-compatible polyfills for Node.js core modules. vite-plugin-node-polyfills is an excellent choice.

Step 1: Install the Plugin

Add the vite-plugin-node-polyfills package to your project as a development dependency:

npm install --save-dev vite-plugin-node-polyfills
# OR
yarn add --dev vite-plugin-node-polyfills
# OR
pnpm add --save-dev vite-plugin-node-polyfills

Step 2: Configure Vite

Update your vite.config.ts (or vite.config.js) file to import and use the plugin. This plugin automatically maps Node.js built-in modules to their browser-compatible counterparts or empty shims when building for the browser.

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nodePolyfills } from 'vite-plugin-node-polyfills'; // Import the plugin

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    nodePolyfills({
      // To exclude specific polyfills (optional)
      exclude: ['http', 'https'],
      // Whether to enable or disable Node.js polyfills in the client build.
      // Set to 'true' by default. Can be a function or a boolean.
      globals: true,
      // Whether to polyfill `node:fs` and `node:path`.
      // The `node:fs` is polyfilled by default, but `node:path` is not.
      buffer: true, // Polyfill 'buffer' module
      process: true // Polyfill 'process' module
    })
  ],
});

After applying this configuration, restart your development server or rebuild your project. The bundler should now correctly resolve the Node.js internal module references without attempting to include server-side code in your client-side bundle.

For Webpack Projects (if applicable)

If you’re using Webpack, the approach involves configuring resolve.fallback in your webpack.config.js to provide polyfills or mock empty modules for Node.js internals.

Step 1: Install Node.js polyfills for Webpack

Install necessary polyfills, for instance, buffer, stream-browserify, and util (among others, depending on what’s implicitly trying to be resolved).

npm install buffer stream-browserify util --save-dev

Step 2: Configure Webpack

Update your webpack.config.js:

const webpack = require('webpack');

module.exports = {
  // ... other configurations
  resolve: {
    fallback: {
      "http": require.resolve("stream-http"),
      "https": require.resolve("https-browserify"),
      "url": require.resolve("url/"),
      "stream": require.resolve("stream-browserify"),
      "util": require.resolve("util/"),
      "buffer": require.resolve("buffer/"),
      // If _http_common is still an issue, it might be nested within 'http' or 'url'.
      // If direct fallback to _http_common is needed (highly unlikely and not standard),
      // you would map it to false or an empty module, but the above should handle it.
      // "_http_common": false, // Or path.resolve(__dirname, 'empty-module.js')
    }
  },
  plugins: [
    // ProvidePlugin makes modules available as global variables
    new webpack.ProvidePlugin({
      process: 'process/browser',
      Buffer: ['buffer', 'Buffer'],
    }),
  ],
  // ... other configurations
};

You might need to install process polyfill as well: npm install process --save-dev.

Common Edge Cases

  • Outdated Dependencies: Ensure all your project dependencies, especially MSW and other related networking libraries, are up to date. Newer versions often have better compatibility with modern bundlers and Node.js versions.
  • Incorrect Build Target: Verify that your bundler is configured to build for the browser environment when you intend to run the code client-side. Sometimes, build scripts can accidentally target Node.js for client bundles.
  • Server-Side Rendering (SSR) Conflicts: If you’re using SSR (e.g., with Next.js, Nuxt, or a custom setup), ensure that your MSW setup correctly differentiates between server and client environments. Node.js polyfills should typically only apply to the client-side bundle.
  • Specific Library Requirements: Some libraries might have unique requirements for polyfills or specific bundler configurations. Always check the official documentation for any library that seems to be triggering this error.
  • Conflicting Bundler Plugins: If you have multiple bundler plugins that affect module resolution or polyfills, they might conflict. Try disabling other related plugins temporarily to isolate the issue.

FAQ

Is this an MSW bug?
No, this is generally not an MSW bug itself. While the error might appear when using MSW, it’s almost always an issue with how your bundler (Vite, Webpack, etc.) is configured to handle Node.js built-in modules when building for a browser environment. MSW relies on standard Web APIs, but if a dependency or the build process incorrectly pulls in Node.js internals, this error occurs.
Why does _http_common appear specifically?
_http_common is a low-level, internal helper module within Node.js’s http and url modules. It’s not directly imported by userland code. When this error surfaces, it implies that a higher-level Node.js built-in module (like http, https, or url) is being improperly included or referenced in your client-side bundle, and the bundler then fails to find its internal dependency, _http_common.
Can I just delete the import for _http_common?
No, attempting to directly delete or ignore the import for _http_common is not a viable solution. It’s an internal dependency required by other Node.js core modules. Removing it would likely cause deeper runtime errors. The correct approach is to provide browser-compatible polyfills or shims for the Node.js modules that ultimately depend on _http_common, effectively telling the bundler how to handle them in a client-side context.

Leave a Reply

Your email address will not be published. Required fields are marked *