Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a webworker in NextJS 10?

I have a Next 10 project where I am trying to use WebWorkers. The worker is being initialized like so:

window.RefreshTokenWorker = new Worker(new URL('../refreshToken.worker.js', import.meta.url))

I also have the Worker defined as

self.addEventListener('message', (e) => {
  console.info("ON MESSAGE: ", e)
  // some logic with e.data
})

Its also being called like this:

const worker = getWorker() // gets worker that is attached at the window level
worker.postMessage('start')

My next.config.js file is defined as

const nextConfig = {
  target: 'serverless',
  env: getBuildEnvVariables(),
  redirects,
  rewrites,
  images: {
    domains: []
  },
  future: { webpack5: true },
  webpack (config) {
    config.resolve.alias['@'] = path.join(__dirname, 'src')
    return config
  }
}

// more definitions

module.exports = nextConfig

The issue I have is the console.info in the Web Worker definition does not receive the message being sent from postMessage on the build version (yarn build && yarn start) but it does on the dev version (yarn dev). Any ways to fix this?

like image 961
Shrey Kumar Avatar asked Nov 07 '25 11:11

Shrey Kumar


1 Answers

This is not a solution. But can be a messy way to do the job. This turned out to be a nightmare for me.

I have the same setup as yours. I was initializing web worker as you have shown in your question. I got this idea from the nextjs doc itself: https://nextjs.org/docs/messages/webpack5

const newWebWorker = new Worker(new URL('../worker.js', import.meta.url))

Everything working correctly when I work in dev mode. it is picking up the worker.js file correctly and everything looks alright.

But when I build the nextjs and try it, then web worker won't work. When I dive deeply into the issues, I found out that the worker.js chunk file is created directly under the .next folder. It should come under .next/static/chunk/[hash].worker.js ideally.

I could not resolve this issue in a proper way.

So what i did, i placed my worker.js file directly under public directory. I put my worker.js file transpiled and optimized and put the code in the public/worker.js file.

After this, I modified the worker initialization like this:

const newWebWorker = new Worker('/worker.js', { type: 'module' });

it is working in the production build now. I will report once I get a cleaner solution for this.

like image 121
Rajeev K Tomy Avatar answered Nov 10 '25 02:11

Rajeev K Tomy