Problem
TypeScript reports a type error in Web Worker files within a Next.js project because the WebWorker global types are not included in the default configuration:
Type error: Cannot find name 'DedicatedWorkerGlobalScope'.
12 | const ctx: DedicatedWorkerGlobalScope = self as any;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
13 |
14 | ctx.onmessage = (event: MessageEvent) => {
error TS2304: Cannot find name 'DedicatedWorkerGlobalScope'.
The worker file that triggers this error:
// workers/heavy-compute.worker.ts
declare const self: DedicatedWorkerGlobalScope;
self.onmessage = (event: MessageEvent) => {
const result = performExpensiveCalculation(event.data);
self.postMessage(result);
};
Solution
Option 1: Add a triple-slash reference directive (recommended)
Add a WebWorker lib reference at the top of each worker file:
// workers/heavy-compute.worker.ts
/// <reference lib="webworker" />
declare const self: DedicatedWorkerGlobalScope;
self.onmessage = (event: MessageEvent) => {
const result = performExpensiveCalculation(event.data);
self.postMessage(result);
};
Option 2: Create a separate tsconfig for worker files
Create a tsconfig.worker.json at the project root:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"lib": ["ESNext", "WebWorker"]
},
"include": ["workers/**/*.ts"]
}
Then configure your IDE to use this config for worker files, or reference it in your build tooling.
Why It Works
Next.js includes DOM and DOM.Iterable in the default tsconfig.json lib array, which provides types for browser globals like window, document, and HTMLElement. However, the WebWorker lib is not included because it conflicts with DOM -- both define overlapping globals like fetch, Request, and Response with slightly different signatures.
The triple-slash /// <reference lib="webworker" /> directive tells TypeScript to include the WebWorker type definitions only for that specific file. This adds types like DedicatedWorkerGlobalScope, SharedWorkerGlobalScope, and ServiceWorkerGlobalScope without polluting the rest of the project with conflicting type definitions.
Context
- Next.js 13+ with App Router or Pages Router, any TypeScript version
- Also applies to
SharedWorkerGlobalScopeandServiceWorkerGlobalScopetypes - Do not add
"WebWorker"to the maintsconfig.jsonlibarray -- it conflicts withDOMtypes and causes duplicate identifier errors forfetch,Request,Headers, etc. - If using a bundler plugin like
worker-loaderor Webpack 5's native worker support, the triple-slash approach is simplest since it requires no build config changes - The
declare const selfpattern is optional if you only usepostMessageandonmessagedirectly, but provides better type safety for the worker context