Skip to content
Get started
Get started
TypeScript SDK: Node.js, Deno, Bun & Cloudflare Workers
View Markdown
sdks · typescript

TypeScript SDK for every JS runtime.

Run the canonical bunqueue API from Node.js 20+, Deno 2+, Bun, and Cloudflare Workers with full type safety, connection pooling, auto-batching, flows, and Simple Mode.

TypeScript SDK

Use bunqueue/client on Bun or bunqueue-client on Node.js, Deno, and Workers

BUN · bunqueue/client Bun App Embedded/TCP Runs embedded SQLite or connects over TCP :6789. Zero-config local dev; swap to server with 1 option. Best for Bun backends & embedded queues NODE / DENO · bunqueue-client Node / Deno Server :6789 Connection pool, auto-reconnect, TLS & pipelining. Full Queue, Worker, Flows & Simple Mode over TCP. Best for Node.js, Deno & edge runtimes
Identical TypeScript API: same Queue, Worker, FlowProducer, QueueEvents, and Simple Mode across every JS runtime.
npm install bunqueue-client

Create one pooled Queue per queue name and enqueue single jobs or batches over TCP (concurrent add() calls auto-batch by default):

import { Queue } from 'bunqueue-client';
const queue = new Queue('emails', {
embedded: false,
connection: {
host: process.env.BUNQUEUE_HOST ?? 'localhost',
port: 6789,
token: process.env.BUNQUEUE_TOKEN,
tls: true, // or { caFile: './ca.pem' }
poolSize: 4, // parallel TCP sockets (default: 4)
commandTimeout: 30_000,
maxInFlight: 100,
},
});
// Single job with priority, retries, and durable flag
await queue.add('welcome', { to: 'user@example.com' }, {
jobId: 'welcome-user-42', priority: 10, attempts: 5, durable: true,
});
// Bulk enqueue (one round-trip; concurrent add() calls also auto-batch by default)
await queue.addBulk(orders.map((o) => ({ name: 'ingest', data: o, opts: { jobId: `order-${o.id}` } })));

Start a concurrent Worker with automatic lease heartbeats, typed error routing (UnrecoverableError, DelayedError, RateLimitError), and graceful SIGTERM draining:

import { UnrecoverableError, Worker } from 'bunqueue-client';
const worker = new Worker('emails', async (job) => {
if (!job.data.to) throw new UnrecoverableError('missing recipient'); // skips retries -> DLQ
await sendEmail(job.data.to);
return { sent: true };
}, {
embedded: false,
connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
concurrency: 10, lockDuration: 30_000, heartbeatInterval: 10_000,
});
worker.on('completed', (job, result) => console.log('done:', job.id, result));
worker.on('failed', (job, err) => console.warn('failed:', job?.id, err.message));
worker.on('error', (err) => console.error('worker error:', err)); // always attach!
process.on('SIGTERM', async () => { await worker.close(); process.exit(0); }); // drains active jobs

Transport and command rejections throw standard Error instances; always attach worker.on('error', ...).

Use *Async queue methods for authoritative TCP reads/mutations, QueueEvents for push-based completion waits, and FlowProducer for atomic job graphs:

import { QueueEvents } from 'bunqueue-client';
// Authoritative TCP reads and mutations
const job = await queue.getJob(id); // null when missing
const state = await queue.getJobState(id);
const counts = await queue.getJobCountsAsync();
await queue.pauseAsync();
const dropped = await queue.drainAsync();
const retried = await queue.retryDlqAsync();
// Wait for completion using QueueEvents (filter broker stream with eventTypes)
const events = new QueueEvents('emails', {
connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
eventTypes: ['completed', 'failed'],
});
await events.waitUntilReady();
const result = await job?.waitUntilFinished(events, 30_000);
events.close();
// Readiness / health probe on Queue, Worker, FlowProducer, or Bunqueue
const health = queue.getHealth(); // PoolHealth | null (null in embedded mode)

Passing null to job.waitUntilFinished(null, 30_000) falls back to polling with extra round-trips and latency compared to QueueEvents.

Atomic trees, chains, and fan-in via FlowProducer:

import { FlowProducer } from 'bunqueue-client';
const flow = new FlowProducer({ embedded: false });
await flow.addChain([
{ name: 'extract', queueName: 'etl', data: {} },
{ name: 'transform', queueName: 'etl', data: {} },
{ name: 'load', queueName: 'etl', data: {} },
]);
await flow.add({
name: 'assemble',
queueName: 'orders',
data: {},
children: [
{ name: 'reserve-stock', queueName: 'orders', data: {} },
{ name: 'charge-card', queueName: 'orders', data: {} },
],
});
await flow.addBulkThen(parts, { name: 'merge', queueName: 'orders', data: {} });

Bundle queue, worker, named routes, middleware, retry policies, and circuit breakers in one object:

import { Bunqueue } from 'bunqueue-client';
const app = new Bunqueue('notifications', {
embedded: false,
connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
routes: {
'send-email': async (job) => ({ sent: true }),
'send-sms': async (job) => ({ sent: true }),
},
concurrency: 10,
retry: { maxAttempts: 5, strategy: 'jitter' },
circuitBreaker: { threshold: 5, resetTimeout: 30_000 },
});
app.on('error', (err) => console.error('app error:', err));
app.use(async (job, next) => {
const start = Date.now();
const out = await next();
console.log(job.name, Date.now() - start, 'ms');
return out;
});
await app.add('send-email', { to: 'alice@example.com' });
await app.cron('daily-digest', '0 9 * * *', { to: 'all' });

Run broker-wide TCP commands (stats, metrics, Prometheus text, storage status, memory compaction, queue/worker/cron/webhook management, queue limits, job inspection, and dashboard snapshots) via BrokerAdmin, which accepts canonical { connection } options (or wraps an existing Connection/ConnectionPool) and reads BQ_TOKEN / BUNQUEUE_TOKEN automatically:

import { BrokerAdmin } from 'bunqueue-client';
const admin = new BrokerAdmin({ connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN } });
await admin.waitUntilReady();
const [stats, queues, limits, prometheus] = await Promise.all([
admin.getStats(), admin.listQueues(), admin.getQueueLimits('emails'), admin.getPrometheusMetrics(),
]);
admin.close();

Enable nodejs_compat in wrangler.toml, enqueue inside fetch handlers (calling disconnect() in finally), and consume in batches from Cron Triggers:

wrangler.toml
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2025-01-01"
import { Queue } from 'bunqueue-client';
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const queue = new Queue('signups', {
embedded: false,
connection: { host: env.BQ_HOST, port: 6789, token: env.BQ_TOKEN, tls: true, poolSize: 1 },
});
try {
const job = await queue.add('welcome', await req.json());
return Response.json({ queued: job.id });
} finally {
await queue.disconnect();
}
},
};
AreaRule / detail
Default modeTCP (embedded: false) unless embedded: true or BUNQUEUE_EMBEDDED=1 is set. Node.js, Deno, and Cloudflare Workers lack bun:sqlite, so pass embedded: false explicitly if that env var may be inherited.
Module & typesPure ESM ("type": "module"); CommonJS Node apps use await import('bunqueue-client') or bundle with esbuild/tsup/Vite. Compile against @types/node 20+.
DenoUse deno add --minimum-dependency-age=0 npm:bunqueue-client if Deno’s age check blocks a new release. Deno skips msgpackr-extract scripts and falls back to pure-JS msgpackr with identical wire output.
TLS & Unix socketsconnection.tls accepts true or file paths (caFile, certFile, keyFile) / inline PEM strings or Buffers (ca, cert, key, passphrase), plus servername (SNI) and rejectUnauthorized (default true). Use connection: { socketPath } for local Unix sockets.
Auth fallback & legacyOmitting connection.token reads BQ_TOKEN or BUNQUEUE_TOKEN across Queue, Worker, FlowProducer, QueueEvents, SandboxedWorker, Bunqueue, and BrokerAdmin. Import bunqueue-client/legacy during incremental 0.1.x migrations.