Unable to load a worklet's module

The React app runs locally without issues, once deployed I get the following runtime error.

Uncaught (in promise) AbortError: Unable to load a worklet's module.

here is the vite config

export default defineConfig({
  plugins: [react(), 
//copy WASM files to destination folder
    viteStaticCopy({
      targets: [
        {
          src: ["**/*.onnx"],
          dest: 'dist',//' onnx web files',
        },
        {
          src: ["node_modules/onnxruntime-web/dist/ort-wasm-*"],
          dest: 'dist',// './',//'wasm-files',
        },
      ],
    }),
  ],
  assetsInclude: ["**/*.onnx"],
  optimizeDeps: {
    exclude: ["onnxruntime-web"],
    esbuildOptions: {
      supported: {
        "top-level-await": true,
      },
    },
  },
  server: {
    headers: {
      //  "Cross-Origin-Opener-Policy": "same-origin",
      "Cross-Origin-Embedder-Policy": "require-corp",
    },
  },
});


and the audioworklet code

import workletUrl from "./audio-processor.ts?url";
 
...
 await audioContext.audioWorklet.addModule(
    new URL(workletUrl, import.meta.url)
  ); // vite requires the meta format and ?url suffix to import a TypeScript file to use it in an AudioWorklet.

the audio-processor.ts file is located in /dist and in /public

This error usually happens when your AudioWorklet module isn’t being properly served or accessible after you deploy to Vercel. A few things to check:

  1. Move your worklet file to the public directory
    Vite serves everything in public as static assets, so it’s the easiest way to make your worklet available.

    public/
      audio-processor.js  // Make sure it’s a .js file
    
  2. Update your import path
    Point directly to the public file:

    await audioContext.audioWorklet.addModule('/audio-processor.js');
    
  3. Add the right headers in vercel.json
    This ensures your worklet and WASM files load correctly:

    {
      "headers": [
        {
          "source": "/(.*\\.(wasm|js))",
          "headers": [
            { "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" },
            { "key": "Cross-Origin-Opener-Policy", "value": "same-origin" }
          ]
        }
      ]
    }
    
  4. Double-check that your worklet file is compiled to JavaScript
    Browsers can’t run TypeScript directly inside worklets, so make sure it’s compiled before deployment.

In most cases, the issue comes down to Vite’s ?url import not generating the correct path in production or the file not being served with the right headers.