Skip to main content
Bun implements the Web Workers API for running JavaScript in parallel threads. Workers are useful for CPU-intensive tasks, parallel processing, and isolating code execution.

Creating a Worker

In worker.ts:

Worker Options

Module Type

Workers can be ES modules or classic scripts:

Worker Name

Name workers for debugging:

Credentials

Control credential passing for module imports:

Communication

Posting Messages

Send data between main thread and worker:

Message Event

Error Handling

Unhandled Rejections

Transferring Data

Structured Clone

By default, data is cloned:
Supported types:
  • Primitives (string, number, boolean)
  • Objects and Arrays
  • Date, RegExp, Map, Set
  • ArrayBuffer, TypedArrays
  • Blob, File, ImageData

Transfer Objects

For better performance, transfer ownership:
Transferable types:
  • ArrayBuffer
  • MessagePort
  • ReadableStream
  • WritableStream
  • TransformStream

Shared Memory

Use SharedArrayBuffer for shared memory:

Worker Lifecycle

Terminating Workers

Inside the worker:

Reference Counting

Control whether worker keeps process alive:

Worker Scope

Global Objects

Inside a worker:

Available APIs

Workers have access to:
  • console
  • setTimeout, setInterval, setImmediate
  • fetch, WebSocket
  • crypto, TextEncoder, TextDecoder
  • URL, URLSearchParams
  • Blob, File, FormData
  • ReadableStream, WritableStream
  • Import maps and ES modules

Not Available

  • DOM APIs (document, window)
  • Most Bun-specific APIs (Bun.serve, etc.)
  • Process-level APIs (process.exit)

Import Maps in Workers

Workers support import maps:

TypeScript

Bun automatically transpiles TypeScript in workers:

Nested Workers

Workers can create other workers:

Common Patterns

Worker Pool

Request-Response Pattern

Progress Updates

Performance Considerations

When to Use Workers

Good use cases:
  • CPU-intensive computations
  • Parsing large data files
  • Image/video processing
  • Cryptographic operations
  • Parallel data processing
Not ideal for:
  • I/O operations (use async instead)
  • Simple computations (overhead not worth it)
  • DOM manipulation (not available in workers)

Minimizing Communication

Message passing has overhead:

Using Transfers

Transfer large buffers instead of cloning:

Debugging Workers

Compatibility

Bun’s Web Workers are compatible with:
  • Browsers (Chrome, Firefox, Safari, Edge)
  • Deno
  • Cloudflare Workers (with some limitations)

Differences from Node.js

Bun implements the standard Web Workers API, not Node.js worker_threads:
Migration tips:
  • Use postMessage instead of parentPort.postMessage
  • Use self.onmessage instead of parentPort.on('message')
  • No workerData - pass data via postMessage