Blog>
Snippets

Using web workers in Next.js for parallel processing

Create a web worker in a Next.js app to perform parallel processing of data-intensive tasks without blocking the main thread.
export default function WorkerSetup() {
  const workerRef = useRef();

  useEffect(() => {
    workerRef.current = new Worker(new URL('../worker.js', import.meta.url));
    workerRef.current.onmessage = (evt) => console.log('Data from worker:', evt.data);
    workerRef.current.onerror = (error) => console.error('Worker error:', error);

    return () => workerRef.current.terminate();
  }, []);

  const runWorkerTask = (data) => {
    workerRef.current.postMessage(data);
  };

  return { runWorkerTask };
}
Initialize a web worker inside a Next.js functional component when the component mounts. The 'workerRef' is a mutable object that will hold our worker instance. Use 'useEffect' to setup the worker and cleanup (terminate) before unmounting. 'runWorkerTask' can be used to post data to the worker for processing.
/* worker.js - Web Worker */

self.onmessage = function({ data }) {
  // Perform intensive data processing here
  const result = processData(data);
  // Post results back to the main thread
  self.postMessage(result);
};

function processData(data) {
  // Simulate a heavy task
  let result = data;
  for(let i = 0; i < 1000000; i++) {
    result += i;
  }
  return result;
}
Create 'worker.js' file which contains the logic for the Web Worker. The 'onmessage' event listener is for receiving data from the main thread. Use 'processData' function to perform heavy computations and then return the result back to the main thread with 'postMessage'.
// In your Next.js page or component
import { useEffect, useState } from 'react';
import WorkerSetup from '../path/to/WorkerSetup';

export default function HomePage() {
  const [result, setResult] = useState();
  const { runWorkerTask } = WorkerSetup();

  useEffect(() => {
    runWorkerTask('Start processing');
  }, []);

  return (
    <div>
      <h1>Web Worker in Next.js</h1>
      <p>Data processed by worker: {result}</p>
    </div>
  );
}
A Next.js component or page uses 'WorkerSetup'. On this example, 'HomePage', we import 'WorkerSetup', and use its 'runWorkerTask' function to start the worker task. This function sends a message to the worker to begin processing. The result is stored in local state and can be used in the component's render output.