- Docs
- SDKs, Recipes & Learning
- Client SDKs (4 Languages)
- TypeScript (Bun / Node / Deno)
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.
Use bunqueue/client on Bun or bunqueue-client on Node.js, Deno, and Workers
Queue, Worker, FlowProducer, QueueEvents, and Simple Mode across every JS runtime.Install
Section titled “Install”npm install bunqueue-clientbun add bunqueue-clientdeno add npm:bunqueue-clientProduce jobs
Section titled “Produce jobs”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 flagawait 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}` } })));Process jobs
Section titled “Process jobs”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 jobsTransport and command rejections throw standard Error instances; always attach worker.on('error', ...).
Query, control, and flows
Section titled “Query, control, and flows”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 mutationsconst job = await queue.getJob(id); // null when missingconst 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 Bunqueueconst 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: {} });Simple Mode (Bunqueue)
Section titled “Simple Mode (Bunqueue)”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' });Broker administration (BrokerAdmin)
Section titled “Broker administration (BrokerAdmin)”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();Cloudflare Workers
Section titled “Cloudflare Workers”Enable nodejs_compat in wrangler.toml, enqueue inside fetch handlers (calling disconnect() in finally), and consume in batches from Cron Triggers:
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(); } },};Runtime caveats
Section titled “Runtime caveats”| Area | Rule / detail |
|---|---|
| Default mode | TCP (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 & types | Pure ESM ("type": "module"); CommonJS Node apps use await import('bunqueue-client') or bundle with esbuild/tsup/Vite. Compile against @types/node 20+. |
| Deno | Use 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 sockets | connection.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 & legacy | Omitting 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. |
See also
Section titled “See also”- SDKs Overview: cross-language architecture and protocol v3 matrix
- Queue API & Worker API: full canonical TypeScript guides
- Source & Changelog