I'm getting this error now: [code]
- User
I'm getting this error now:
⨯ NormalModuleFactory.beforeResolve (, IgnorePlugin) is no longer a waterfall hook, but a bailing hook instead. Do not return the passed object, but modify it instead. Returning false will ignore the request and results in no module created. Assistant
You are absolutely right! My apologies. The error message indicates that the
beforeResolvehook onNormalModuleFactorywas changed from awaterfallhook to abailinghook in a later version of Webpack.Here's the breakdown:
- Waterfall Hook (Old behavior): You return the (potentially modified) value you received. This value is then passed as input to the next tap in the chain. The final return value of the hook is the return value of the last tap.
- Bailing Hook (New behavior): If a tap returns any value other than
undefined, the hook stops executing immediately, and that returned value becomes the final result of the hook. If a tap returnsundefined(or has no explicitreturnstatement), the hook continues to the next tap. Returningfalsespecifically signals that the request should be ignored entirely.
Your original code was returning the
dataobject (return data;), which is the behavior of a waterfall hook. In a bailing hook, this causes it to stop processing after your plugin runs, preventing other plugins (like Webpack's built-in ones or others you might have) from also tapping intobeforeResolve.The fix: Modify the
dataobject in place and returnundefined(or simply nothing) to allow other taps to run.Here's the corrected
strip-node-protocol-plugin.js:// strip-node-protocol-plugin.js // Corrected version for Webpack bailing hooks /** * Webpack plugin that turns * import dns from 'node:dns' * into * import dns from 'dns' * * It intercepts the "beforeResolve" step of the * NormalModuleFactory and modifies the request string in-place. * * Uses a bailing hook correctly by returning nothing (undefined) * after modifying the data. */ class StripNodeProtocolPlugin { constructor() { this.pluginName = 'StripNodeProtocolPlugin'; this.prefix = 'node:'; } apply(compiler) { compiler.hooks.normalModuleFactory.tap(this.pluginName, nmf => { // Tap into the beforeResolve hook. // This is a bailing hook as of recent Webpack versions. nmf.hooks.beforeResolve.tap(this.pluginName, data => { // `data` might be undefined or lack request for certain cases // (e.g., sometimes with loaders or specific webpack configs). // If we can't process it, let it pass through by returning nothing. if (!data || !data.request) { return; // Explicitly return undefined, or just end the function } // Check if the request starts with the 'node:' prefix if (data.request.startsWith(this.prefix)) { // Modify the request string IN PLACE. // This is the key difference for bailing hooks - mutate the object // instead of returning a new one or the modified one. data.request = data.request.slice(this.prefix.length); // IMPORTANT: After modifying, return nothing (undefined) // This signals to the bailing hook that it should continue // executing the *next* tap in the chain. // Returning `data` (like before) would prematurely stop the hook. // Returning `false` would skip resolution entirely for this module. return; // Explicitly return undefined } // If the prefix wasn't there, do nothing and return undefined // so other taps can process the request. return; // Explicitly return undefined }); }); } } module.exports = StripNodeProtocolPlugin;Key Changes:
- Inside the
beforeResolvetap, after modifyingdata.request, we now explicitlyreturn;which returnsundefined. - The initial check
if (!data || !data.request) return data;was also returningdata. It's changed to justreturn;so that even in these unhandleable cases, the hook doesn't bail prematurely.
Keep the usage in
next.config.jsthe same, just ensure you are using this correctedstrip-node-protocol-plugin.jsfile.// next.config.js const path = require('path'); const webpack = require('webpack'); const StripNodeProtocolPlugin = require('./strip-node-protocol-plugin'); // Make sure this path is correct module.exports = { // ... other next.config.js settings ... webpack: (config, { isServer, webpack }) => { // ... your existing next-js tweaks ... // Add the corrected plugin // Ensure it's early in the list if you want other plugins/loaders // to see the stripped request, but putting it first is generally safe. config.plugins.unshift(new StripNodeProtocolPlugin()); return config; }, };This corrected version respects the bailing nature of the
beforeResolvehook and should eliminate the warning while achieving the desired request modification.- User
I went with this code:
class NodePrefixStripPlugin { apply(compiler) { compiler.hooks.normalModuleFactory.tap('NodePrefixStripPlugin', (factory) => { factory.hooks.beforeResolve.tap('NodePrefixStripPlugin', (resolveData) => { if (resolveData.request.startsWith('node:')) { resolveData.request = resolveData.request.slice(5); } return true; // Return true to continue module resolution }); }); } }Now I'm getting this error:
⨯ ./node_modules/dd-trace/packages/datadog-instrumentations/src/net.js:28:1 Module not found: Can't resolve 'dns' Did you mean './dns'? Requests that should resolve in the current directory need to start with './'. Requests that start with a name are treated as module requests and resolve within module directories (node_modules). If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too. Assistant
Okay, you're getting a new error, and this is a different type of problem. The plugin is successfully stripping the
node:prefix, but now Webpack is trying to resolve the resulting module name (dns) and failing.The error message
Module not found: Can't resolve 'dns'indicates that Webpack looked for a module nameddns(after your plugin changednode:dnstodns) and couldn't find it anywhere it expected to find modules (likenode_modules).Why is this happening?
- Webpack Targeting Browser: When Next.js builds for the client (
!isServer), Webpack is configured for a browser environment. Browser environments do not have Node.js built-in modules likedns,fs,net,tls, etc. - Your
resolve.fallbackConfig: You have explicitly configured Webpack for the client (!isServer) with:
This tells Webpack: "If you encounter an import forconfig.resolve.fallback.dns = false; // <-- Here it is!dnsand can't resolve it conventionally (relative path, node_modules), do not provide any fallback and instead treat it as an error." - The Interaction: Your plugin changes
node:dnstodns. Webpack then tries to resolvedns. It checks yourresolve.fallbackconfiguration fordns, seesfalse, and correctly throws the "Module not found" error because you told itdnsshould not be available. - Source of the Import (
dd-trace): The error message points to/node_modules/dd-trace/.../net.js. This strongly suggests that thednsimport is coming from thedd-tracelibrary.dd-traceis a Node.js server-side tracing library. It relies heavily on Node.js built-ins likedns,net,tls,fs, etc., to instrument network and file system operations. It is generally not meant to run in a browser environment.
There are two primary issues here:
- Incorrect Plugin Return Value: Your latest plugin code uses
return true;. As the previous error message indicated,beforeResolveis a bailing hook. Returningtrue(or any non-undefinedvalue other thanfalse) tells Webpack to stop processing this hook immediately for this request. While it might allow the resolution to continue, the correct way to signal "I modified the data, continue with the modified data" for a bailing hook is to return nothing (undefined). Returningtruemight have unintended side effects or become a problem in combination with other plugins. - Including Server-Only Code (
dd-trace) in the Client Bundle: The root cause is that thedd-tracelibrary, which requires Node.js built-ins, is somehow being included in your client-side bundle.
Let's fix both:
1. Correct the Plugin Return Value (Again)
Change
return true;to simplyreturn;(or omit the return statement entirely after modifyingresolveData).// strip-node-protocol-plugin.js class NodePrefixStripPlugin { apply(compiler) { compiler.hooks.normalModuleFactory.tap('NodePrefixStripPlugin', (factory) => { factory.hooks.beforeResolve.tap('NodePrefixStripPlugin', (resolveData) => { // Add null/undefined check for safety if (!resolveData || !resolveData.request) { return; // Let other taps handle it or bail if they need to } if (resolveData.request.startsWith('node:')) { resolveData.request = resolveData.request.slice(5); // IMPORTANT: Return nothing (undefined) to allow other taps/resolution // to continue with the modified request. return; } // If no modification happened, return nothing (undefined) as well // so other taps can process the original request. return; }); }); } } module.exports = NodePrefixStripPlugin; // Make sure you're exporting the class2. Address the "Module not found: Can't resolve 'dns'" Error
This error happens because
dnsis being requested on the client side, and you've explicitly disabled it withresolve.fallback.dns = false. You have two main options:Option A (Recommended): Prevent
dd-trace(and other server-only code) from being bundled client-side.This is the most robust solution. Libraries like
dd-tracecannot run in the browser. Ensure that any code that imports or requiresdd-traceis only executed on the server. In Next.js, this typically means:- Importing
dd-traceonly insideif (isServer)blocks. - Importing
dd-traceonly in files underpages/api/(API routes). - Importing
dd-traceonly within functions likegetServerSideProps,getStaticProps(thoughgetStaticPropscode runs during build and shouldn't need tracing), or API routes. - Using dynamic imports (
import('dd-trace')) wrapped in anif (isServer)check.
You already have a
NormalModuleReplacementPluginfordd-traceon the client, which is a good step. Make sure it's applied correctly and thatdd-traceisn't being imported in a way that bypasses this (less likely). Ideally, you wouldn't even need the replacement plugin if the code paths are correctly isolated.Option B (Workaround): Tell Webpack to replace these built-ins with empty modules on the client.
Instead of setting
fallbacktofalse, you can set it to'empty'. This is a common pattern for stubbing out server-only modules that might accidentally get included in the client bundle. This effectively tells Webpack: "If you see an import fordns(ornet,tls, etc.) on the client, replace it with a minimal, empty module."Modify your
next.config.js:// next.config.js const path = require('path'); const webpack = require('webpack'); // Make sure this path is correct const NodePrefixStripPlugin = require('./strip-node-protocol-plugin'); // Define your assetPrefix if needed const assetPrefix = process.env.ASSET_PREFIX || ''; module.exports = { assetPrefix, // Apply assetPrefix if defined webpack: (config, { isServer, webpack }) => { // Add the prefix stripping plugin early config.plugins.unshift(new NodePrefixStripPlugin()); // Fallback configuration config.resolve.fallback = { ...config.resolve.fallback, // Preserve existing fallbacks // fs: false, // You might want to remove this initial setting if the conditional below handles it // For the client build, provide 'empty' fallbacks for Node.js built-ins // that might accidentally be included. // Note: Keeping fs: false might be intentional if you absolutely // don't want fs included even as an empty object. // Change 'false' to 'empty' for modules causing errors like 'dns'. }; if (!isServer) { // Client-side specific fallbacks // Change 'false' to 'empty' for the modules causing "Module not found" // You might need to do this for dns, net, tls, async_hooks, etc. // Keep others as false if you want to ensure they throw errors. config.resolve.fallback.fs = false; // Or 'empty' if needed config.resolve.fallback.dns = 'empty'; // <--- Change false to 'empty' config.resolve.fallback.net = 'empty'; // <--- Change false to 'empty' config.resolve.fallback.tls = 'empty'; // <--- Change false to 'empty' config.resolve.fallback.async_hooks = 'empty'; // <--- Change false to 'empty' config.resolve.fallback.path = 'empty'; // <--- Change false to 'empty' (path sometimes causes issues) // Your existing replacement plugin for the whole dd-trace package // This is a good approach to ensure dd-trace is not included client-side. // The 'empty' fallbacks are a fallback *for the imports within* dd-trace // in case the module replacement isn't perfect or if other libraries // also try to import these built-ins. config.plugins.push( new webpack.NormalModuleReplacementPlugin( /dd-trace/, path.resolve(__dirname, 'mocks/empty.js'), ), ); } else { // Server-side config // On the server, Node.js built-ins *should* resolve correctly // without fallbacks, as they are provided by the Node.js runtime. // Ensure you don't set these to false or 'empty' on the server. config.devtool = 'source-map'; // server-side fallbacks can be useful for things like 'canvas' or 'xmlhttprequest' // that exist in node_modules but you might want to mock or exclude. // config.resolve.fallback = { ...config.resolve.fallback, 'canvas': false }; } // Your existing string-replace-loader rule config.module.rules.push({ test: /.*.(js|ts)$/, // Use 'pre' or 'post' enforce if needed, but 'normal' is usually fine // enforce: 'pre', loader: 'string-replace-loader', options: { search: '/_next/data', // Make sure assetPrefix is correctly handled, potentially needs a leading slash if it's just a domain/subpath replace: `${assetPrefix}/_next/data`, }, }); return config; }, };Summary:
- Update your
strip-node-protocol-plugin.jsto returnundefinedinstead oftruefrom thebeforeResolvetap. - The "Module not found" error is due to your
resolve.fallback.dns = falsesetting on the client interacting with the strippeddnsrequest. - The best solution is to ensure server-only code like
dd-traceis never bundled for the client. - A necessary workaround, if server-only imports are hard to avoid entirely in the client bundle, is to change
resolve.fallback.moduleName = falsetoresolve.fallback.moduleName = 'empty'for the specific Node.js built-ins causing errors on the client side (dns,net,tls,async_hooks,path, etc.). Your existingNormalModuleReplacementPluginfordd-traceis also a good strategy for this.
- Webpack Targeting Browser: When Next.js builds for the client (
- User
This error happens when nextjs compiles the middleware file, looking at nextjs' docs, it seems like the middleware runs on their
edgeruntime. Do you think that has anything to do with this ? Assistant
Yes, absolutely! Your observation about Next.js Middleware running on the "Edge Runtime" is highly relevant and very likely the cause of the new error.
Here's why:
- Edge Runtime Limitations: The Next.js Edge Runtime (based on Web standards and V8 isolates, not a full Node.js environment) provides a limited set of Node.js APIs. It does not include many standard Node.js modules like
dns,net,tls,fs,async_hooks, etc. The goal is fast startup and low resource usage, suitable for edge environments. dd-traceDependency: As we discussed,dd-traceis a Node.js tracing library designed to instrument Node.js applications. It relies heavily on Node.js built-in modules that are fundamental to the Node.js environment, includingdns,net,tls, etc., to hook into system calls and network operations.- The Conflict: When Next.js compiles your middleware, it uses a Webpack configuration specifically targeting the Edge Runtime. If any code within your middleware file, or any module it imports, tries to
requireorimporta Node.js built-in that is not available in the Edge Runtime (likedns), the build will fail with a "Module not found" error. - Your Plugin and Fallbacks Don't Help Here:
- Your
NodePrefixStripPluginsuccessfully changesnode:dnstodns. But the problem isn't the prefix; it's thednsmodule itself being unavailable in the target environment. - Your
resolve.fallbackconfiguration innext.config.jsprimarily applies to the client build (browser) and sometimes the server build (full Node.js, but built-ins are usually just there). The Webpack configuration Next.js uses internally for the middleware (Edge Runtime) compilation is separate and doesn't necessarily inherit theseresolve.fallbacksettings in the same way. It's configured to fail resolution for modules not present in the Edge environment.
- Your
The core issue is that you are trying to include a library (
dd-traceor something it depends on) that requires Node.js built-ins within code (middleware) that is compiled for an environment (Edge Runtime) that does not have those built-ins.Solution:
The
dd-tracelibrary is fundamentally incompatible with the Edge Runtime. You must not import or requiredd-traceor any other library that requires full Node.js built-ins directly within your middleware file or any modules it imports.Tracing with
dd-traceshould happen in your server-side Node.js code, such as:- Your API routes (
pages/api/). - Inside
getServerSideProps. - Any other custom server-side code you might have running in a full Node.js environment (e.g., a custom server.js).
In summary:
- Your plugin is likely working correctly to strip the
node:prefix. - The error
Module not found: Can't resolve 'dns'when compiling middleware means a dependency is trying to importdns. - This dependency is likely
dd-trace(or something it pulls in) because it relies on Node.js built-ins. - Next.js middleware runs on the Edge Runtime, which does not have the
dnsbuilt-in (or most others needed bydd-trace). - Therefore, you cannot use
dd-tracewithin your Next.js middleware. You need to ensure it's only imported and used in code paths that run in a full Node.js environment.
- Edge Runtime Limitations: The Next.js Edge Runtime (based on Web standards and V8 isolates, not a full Node.js environment) provides a limited set of Node.js APIs. It does not include many standard Node.js modules like
- User
I cannot use the nodejs runtime because it is an experimental feature. Is there a way to stub the dd trace import when the middleware is imported, without actually removing the dd-trace import from the middleware ?
(for context, the dd-trace import is being done further down a chain of imports starting in the middleware. The code that the middleware imports won't really use the dd-trace code)
Assistant
Okay, you're in a common scenario where a dependency chain pulls in server-only code into an environment where it shouldn't run (Edge Runtime for middleware).
Since you cannot modify the source code to remove the import or add
if (isServer)checks easily down the chain, and the Node.js runtime for middleware is experimental, the standard solution is to use Webpack's capabilities to replace the unwanted module with a dummy module during the middleware compilation step.We can use
webpack.NormalModuleReplacementPluginorwebpack.IgnorePlugin. Sincedd-tracelikely has methods (.init,.trace, etc.) that might be called even if the code path doesn't fully execute, replacing it with a simple mock that has dummy methods is safer than just ignoring it, which could lead to runtime errors when the imported object is used.We need to apply this replacement only when Webpack is compiling the middleware, not the server build. Next.js's Webpack config for middleware uses the
target: 'edge'setting. We can use this flag to conditionally apply the plugin.Here's the plan:
- Create a small mock file for
dd-trace. - In
next.config.js, check ifconfig.target === 'edge'. - If it is, add a
NormalModuleReplacementPluginto replacedd-traceimports with the path to your mock file.
Step 1: Create the Mock File
Create a file, for example,
mocks/dd-trace-edge-mock.js:// mocks/dd-trace-edge-mock.js // This is a mock for the dd-trace library specifically for the Edge Runtime. // It prevents build errors by providing a dummy module with no functionality. // Any calls to methods on the imported object will simply do nothing. // Optional: Log a warning during build/startup to indicate the mock is being used console.log("WARN: Using dd-trace mock for Edge Runtime."); const noOp = () => {}; // Create a dummy object that mimics the expected interface of dd-trace // Add more dummy methods/properties if your code calls others const mockTracer = { init: (config) => { // console.log("WARN: dd-trace mock init called."); return mockTracer; // Return itself to allow chaining }, trace: (name, options, fn) => { // console.log(`WARN: dd-trace mock trace called for ${name}.`); // If a function is provided as the last argument (the traced operation) // just execute it directly, passing a dummy span object. if (typeof options === 'function') { fn = options; options = {}; } try { // Provide a minimal mock span if the function expects one const mockSpan = { finish: noOp, context: () => ({}), // Return a dummy context // Add other span methods if needed: setTag, setError, etc. }; return fn(mockSpan); } catch (error) { console.error("Error in dd-trace mock execution:", error); throw error; // Re-throw original errors } }, wrap: (name, options, fn) => { // console.log(`WARN: dd-trace mock wrap called for ${name}.`); // Just return the original function, don't wrap if (typeof options === 'function') { fn = options; options = {}; } return fn; }, startSpan: (name, options) => { // console.log(`WARN: dd-trace mock startSpan called for ${name}.`); // Return a minimal mock span return { finish: noOp, context: () => ({}), }; }, // Add other methods or properties if your code expects them scope: { active: null, // Or return a dummy span if you expect an active span activate: (span, fn) => { // console.log(`WARN: dd-trace mock scope.activate called.`); if (typeof fn === 'function') { fn(); } }, bind: (callback) => callback, // Just return the callback // Add other scope methods like active, bind, etc. }, // Add other top-level properties if accessed directly, e.g., format // format: {}, }; // dd-trace is typically required and then .init() is called on the result module.exports = mockTracer;Note: You might need to add more dummy methods (
setTag,setError,bind,active, etc.) to themockTracerandmockSpanobjects if the code in your dependency chain calls them directly. Inspect the error messages or the code if you get runtime errors.Step 2: Update
next.config.jsModify your
next.config.jsto include the conditional replacement plugin:// next.config.js const path = require('path'); const webpack = require('webpack'); // Assuming your plugin is in ./strip-node-protocol-plugin.js const NodePrefixStripPlugin = require('./strip-node-protocol-plugin'); // Define your assetPrefix if needed const assetPrefix = process.env.ASSET_PREFIX || ''; module.exports = { assetPrefix, // Apply assetPrefix if defined // Important: Add the middleware.edgePaths config if you are using it // This explicitly tells Next.js which files compile to the edge runtime. // Ensure the file importing dd-trace is covered by this config if applicable. // middleware: { // edgePaths: [ // 'src/middleware.ts', // Example: Your middleware file // // Add any other files that should compile to edge // ], // }, webpack: (config, { isServer, webpack, config: { experimental } }) => { // Add your existing node: prefix stripping plugin early config.plugins.unshift(new NodePrefixStripPlugin()); // --- Start Edge Runtime / Middleware Specific Configuration --- // Check if the current compilation target is 'edge' (used for middleware) if (config.target === 'edge') { console.log("Applying Edge Runtime specific Webpack config (stubbing dd-trace)"); // Path to your mock file const ddTraceMockPath = path.resolve(__dirname, 'mocks/dd-trace-edge-mock.js'); // Use NormalModuleReplacementPlugin to replace the actual dd-trace module // with the mock file during the edge compilation. // The regex /^dd-trace(\/|$)/ matches 'dd-trace' or 'dd-trace/...' config.plugins.push( new webpack.NormalModuleReplacementPlugin( /^dd-trace(\/|$)/, ddTraceMockPath ) ); // Also, you might need to stub other Node.js built-ins that dd-trace // or its dependencies might *still* try to import, even after the // module replacement, if the mock isn't perfect or if other Edge-incompatible // modules are pulled in. // You could potentially add fallbacks for these *only* in the edge config, // but it's better to rely on the module replacement if possible. // If you see "Module not found" errors for 'dns', 'net', etc. during the // *middleware* build, you might need edge-specific fallbacks. // However, fallbacks often replace built-ins with npm packages, which // likely also won't work in the Edge runtime. // The most reliable approach is ensuring the problematic module (dd-trace) // is fully replaced before its dependencies are even considered. // If you still get errors for built-ins, double-check that the // dd-trace replacement is happening correctly or if another edge-incompatible // library is being imported. // Edge runtime is minimal, ensure other node modules are not included // These are often implicitly handled by the edge target, but explicit // ignores might be necessary depending on dependencies. // config.plugins.push( // new webpack.IgnorePlugin({ // resourceRegExp: /^(dns|net|tls|fs|async_hooks|...)(\/|$)/, // }) // ); } // --- End Edge Runtime / Middleware Specific Configuration --- // --- Start Client-side (isServer = false) Specific Configuration --- // Keep your existing client-side fallbacks and replacements here. // These apply to the browser bundle, not the middleware. if (!isServer) { // Client-side specific fallbacks. 'empty' is safer than false // if the module might be accidentally imported. config.resolve.fallback = { ...config.resolve.fallback, fs: false, // Keep as false or change to 'empty' if needed client-side dns: 'empty', // Use 'empty' for modules that cause errors client-side net: 'empty', tls: 'empty', async_hooks: 'empty', path: 'empty', // path can cause issues client-side too // Add other Node.js built-ins that cause client errors }; // Your existing replacement plugin for dd-trace on the client side // This is separate from the Edge replacement. It's good practice // to exclude dd-trace from the client bundle too. config.plugins.push( new webpack.NormalModuleReplacementPlugin( /dd-trace/, path.resolve(__dirname, 'mocks/empty.js'), // Use your general empty mock ), ); } // --- End Client-side Specific Configuration --- // --- Server-side (isServer = true) Specific Configuration --- // On the server, Node.js built-ins should resolve naturally. // Don't set them to false or 'empty' here unless you have a specific reason. else { config.devtool = 'source-map'; // Example server-side config // server-side fallbacks could be for modules that exist in node_modules // but you don't want to include on the server, like certain UI libraries. // config.resolve.fallback = { ...config.resolve.fallback, 'canvas': false }; } // --- End Server-side Specific Configuration --- // Your existing string-replace-loader rule (applies to both client and server by default) // If you only need this on one target, add an if(isServer) or if(!isServer) check // If you need it on edge, you might need another check: if (isServer || config.target === 'edge') config.module.rules.push({ test: /.*.(js|ts)$/, loader: 'string-replace-loader', options: { search: '/_next/data', replace: `${assetPrefix}/_next/data`, }, }); return config; }, };Explanation:
config.target === 'edge': Next.js exposes the Webpack configuration target in theconfigobject passed to thewebpackfunction. The middleware compilation uses the'edge'target. This is our reliable flag.- Conditional Plugin: We wrap the
NormalModuleReplacementPlugincreation inside anif (config.target === 'edge')block. This ensures this plugin is only added when compiling for the Edge Runtime. NormalModuleReplacementPlugin(/^dd-trace(\/|$)/, ddTraceMockPath):- The first argument
^dd-trace(\/|$)is a regular expression. It matches any import/require for'dd-trace'exactly, or'dd-trace/'followed by something else (like'dd-trace/some/path'). This ensures all parts of thedd-tracepackage are targeted. - The second argument
ddTraceMockPathis the absolute path to your dummy mock file. Webpack will replace any matched request with an import of this mock file instead of the realdd-tracepackage.
- The first argument
- Mock File (
dd-trace-edge-mock.js): This file exports a basic object with dummy methods. When the code in your dependency chain tries to dorequire('dd-trace').init(...), it will instead get the object exported bydd-trace-edge-mock.js, and callmockTracer.init(), which simply returns the mock object itself, preventing a runtime error. Other method calls like.trace()are also stubbed. - Separation of Concerns: Notice how the client-side fallback configuration (
!isServer) remains separate. The problems on the client (browser) are different from the problems in the Edge Runtime (minimal Node.js APIs). We use different strategies ('empty'fallback vs. specific module replacement) and different mock files (mocks/empty.jsvs.mocks/dd-trace-edge-mock.js) tailored to the environment's needs and how the module is likely used.
By implementing this, the
dd-traceimport will be replaced by the harmless mock during the middleware build, resolving the "Module not found: Can't resolve 'dns'" error which was a consequence of trying to bundledd-tracefor the Edge Runtime.- Create a small mock file for
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.