next-worker

Web Workers for Next.js

example.worker.js
onmessage = (e) => {
  postMessage("Hello from World!")
}
example.jsx
import useWorker from 'next-worker';
 
function ExampleComponent() {
  const { postMessage } = useWorker("example.worker.js", e => console.log(e));
 
  useEffect(() => {
    postMessage("Hello world!");
  }, []);
 
  return <></>
}

In this example, the useWorker hook takes a fileName of the worker and a listener function. useWorker spawns a worker with fileName, on mount. Incoming messages are listened through listener. The hook returns a postMessage function to send messages to the spawned worker.