typescriptnext.jsworkerstockfishturbopack

Typescript error TP1001 when creating a Web Worker in Next.js 15.0.2 with Stockfish chess engine


I'm working on a Next.js 15.0.2 project with turbopack using TypeScript, and I'm integrating the Stockfish chess engine to create a Web Worker on the client side.

The Stockfish library is stored in the public folder, and the client fetches it and creates the Worker with the following code:

const stockfishPath = '/stockfish/stockfish-nnue-16-single.js';

const createStockfishWorker = () => {
  try {
    const worker = new Worker(stockfishPath);
    return worker;
  } catch (error) {
    throw Error(`Initialize stockfish worker failed: ${error}`);
  }
};

export default createStockfishWorker;

The Stockfish library loads and works perfectly in the client. However, when I run the project, I get the following TypeScript error in the console:

GET /analysis/w 200 in 2089ms
⚠ ./src/services/stockfish/createStockfishWorker.ts:7:20
error TP1001 new Worker("/stockfish/stockfish-nnue-16-single.js") is not statically analysable
   5 | const createStockfishWorker = () => {
   6 |   try {
>  7 |     const worker = new Worker(stockfishPath);
     |                    ^^^^^^^^^^^^^^^^^^^^^^^^^
   8 |     postMessage(['uci'], worker);
   9 |     return worker;
  10 |   } catch (error) {

What I tried:

My setup:

What I need help with:

Any help or suggestions would be greatly appreciated!


Solution

  • use window.Worker instead of Worker

    const worker = new window.Worker(stockfishPath);
    

    Typescript error TP1001 when creating a Web Worker in Next.js 15.1.3