Workly for TypeScript
The TypeScript SDK for Workly, the open-source HTTP task queue. Enqueue a task, and Workly delivers it to your endpoint over HTTP, retrying with backoff until it succeeds.
npm install @worklydev/sdkNo dependencies. It uses fetch and Web Crypto, so it runs on Node 22+, Bun, Deno and edge runtimes (Cloudflare Workers, Vercel Edge). ESM, with types included.
Quickstart
Section titled “Quickstart”Start a local server with workly dev (SQLite, no auth, on :7337; pip install "workly[cli]" or curl -fsSL https://raw.githubusercontent.com/worklydev/workly/main/install.sh | sh), then:
import { Workly } from '@worklydev/sdk';
const workly = new Workly(); // WORKLY_URL, else http://localhost:7337; WORKLY_API_KEYconst task = await workly.tasks.enqueue('emails', { url: 'https://api.example.com/send-email', payload: { userId: 123 },});console.log(task.id, task.state);Your endpoint receives a POST with the JSON payload. Any 2xx marks the task succeeded. A 5xx, 408, 429, timeout or connection error is retried with backoff. Delivery is at-least-once, so make handlers safe to run twice. Workly-Task-Id is stable across attempts and works as a deduplication key.
Verifying deliveries
Section titled “Verifying deliveries”Every delivery is signed: with the server’s WORKLY_SIGNING_SECRET when you run Workly yourself, or with your workspace’s secret on workly.run. Check the signature against the raw body, before parsing it:
import { SignatureVerificationError, verifySignature } from '@worklydev/sdk';
// Next.js route handler, Hono, Cloudflare Workers: anything with a Fetch API Requestexport async function POST(request: Request) { const body = await request.text(); try { await verifySignature(body, request.headers); // secret from WORKLY_SIGNING_SECRET } catch (err) { if (err instanceof SignatureVerificationError) return new Response(null, { status: 401 }); throw err; } const payload = JSON.parse(body); // ...}
// Express: keep the raw bodyapp.post('/send-email', express.raw({ type: '*/*' }), async (req, res) => { await verifySignature(req.body, req.headers, secret); // ...});By default, signatures older than 5 minutes are rejected ({ toleranceSeconds }). workly dev signs with workly-dev-secret. To test your handler without a server, await sign(body, secret) returns the headers Workly would send.
Hosted Workly
Section titled “Hosted Workly”On workly.run, point the client at the hosted API and use the keys from the console:
export WORKLY_URL=https://api.workly.runexport WORKLY_API_KEY=... # API keys pageexport WORKLY_SIGNING_SECRET=whsec_... # same page; each workspace has its ownNothing else changes. Hosted workspaces have a request rate limit and a monthly task quota: requests over the rate limit are retried for you, and an enqueue over the quota throws a PermissionDeniedError with the code quota_exceeded.
await workly.tasks.enqueue('emails', { url: 'https://api.example.com/send-email', payload: { userId: 123 }, // JSON, sent as is; or body: 'raw text', contentType: 'text/csv' method: 'POST', // default headers: { 'X-Tenant': 'acme' }, // sent with every delivery delaySeconds: 60, // or runAt: new Date(...) idempotencyKey: 'welcome-123', // an existing task with this key is returned instead maxAttempts: 5, // overrides the queue's setting timeoutSeconds: 10, // likewise});
// Up to 100 at once, all or nothing.await workly.tasks.enqueueMany( 'emails', users.map((u) => ({ url: 'https://api.example.com/send-email', payload: { userId: u.id } })),);
const task = await workly.tasks.get('task_01J9...');for (const attempt of await workly.tasks.attempts(task.id)) { console.log(attempt.number, attempt.outcome, attempt.statusCode, attempt.durationMs);}
await workly.tasks.retry(task.id); // run now; replays a finished taskconst delivery = await workly.tasks.delivery(task.id); // the signed request, to replay by handawait workly.tasks.cancel(task.id);
// Newest first, across pages. All filters are optional.for await (const task of workly.tasks.list({ queue: 'emails', state: 'failed', createdAfter: new Date(Date.now() - 24 * 3600 * 1000),})) { // ...}Field names are camelCase: the SDK converts them to and from the API’s snake_case (retry_on_4xx is retryOn4xx). Payloads and headers are your own data, so they are sent and returned exactly as they are. Timestamps are RFC 3339 strings, and fields added by newer servers come through too.
Queues
Section titled “Queues”Queues are created automatically on first enqueue. put sets a queue’s configuration declaratively, which makes it easy to keep in code: settings you leave out are reset to their defaults.
await workly.queues.put('emails', { maxAttempts: 10, minBackoffSeconds: 1, maxBackoffSeconds: 3600, backoffMultiplier: 2, timeoutSeconds: 30, ratePerSecond: 50, maxConcurrency: 20, autoPause: { afterFailures: 20 }, // pause after 20 failures in a row, until a probe succeeds});
const queue = await workly.queues.get('emails');console.log(queue.stats?.due, queue.stats?.oldestDueAt);
await workly.queues.pause('emails'); // stop delivering; enqueueing still worksawait workly.queues.resume('emails');await workly.queues.cancelPending('emails'); // cancel pending tasksawait workly.queues.retryFailed('emails'); // replay failed tasks, e.g. after an outagefor (const group of await workly.queues.failures('emails')) { console.log(group.count, group.error); // failed tasks grouped by error}await workly.queues.retryFailed('emails', { lastError: 'HTTP 503 Service Unavailable' }); // replay one groupawait workly.queues.activity('emails'); // succeeded/failed/cancelled in the last 7 daysawait workly.queues.delete('emails'); // delete the queue and all its tasksSchedules
Section titled “Schedules”A schedule calls a URL on a cron timetable; each call is a run, retried and recorded like a task. Schedules are separate from queues. put is declarative, like queues.put. See Schedules.
const schedule = await workly.schedules.put('nightly-report', { cron: '0 3 * * *', timezone: 'Europe/Stockholm', url: 'https://api.example.com/reports/nightly', payload: { kind: 'daily' }, maxAttempts: 3, overlap: 'skip', // skip a slot while the previous run is still going});console.log(schedule.nextRuns); // the next five times
const run = await workly.schedules.trigger('nightly-report'); // run it nowfor await (const r of workly.runs.list({ schedule: 'nightly-report', state: 'failed' })) { console.log(r.id, r.scheduledFor, r.lastError);}await workly.runs.attempts(run.id);await workly.runs.retry(run.id); // deliver it again, e.g. a failed or skipped runawait workly.schedules.pause('nightly-report');await workly.schedules.resume('nightly-report'); // from the next scheduled timeawait workly.schedules.delete('nightly-report'); // with all its runsRuns are delivered with Workly-Run-Id, Workly-Schedule and Workly-Scheduled-For headers and the same signature, so verifySignature works unchanged.
Task groups
Section titled “Task groups”A group tracks a set of tasks and enqueues a callback task once it’s closed and they’ve all finished: a POST of the group’s status and counts. See Task groups. Like every callback, it goes to Workly’s _callbacks queue.
groups.enqueue does the whole job in one call: it creates the group, enqueues the tasks into it in batches of 100 and closes it, and it’s safe to retry with the same idempotencyKey.
const group = await workly.groups.enqueue( 'stock-prices', companies.map((c) => ({ url: 'https://api.example.com/jobs/update-stock-price', payload: { symbol: c.symbol } })), { name: 'daily-stock-prices', idempotencyKey: 'stock-prices-2026-10-19', // a retry finishes this group rather than start another onComplete: { url: 'https://api.example.com/jobs/refresh-views' }, },);Or step by step: workly.groups.create(...), then workly.tasks.enqueue(..., { groupId: group.id }) or enqueueMany for each task, then workly.groups.close(group.id), after which it completes once its tasks have finished.
const g = await workly.groups.get(group.id);console.log(g.status, g.total, g.succeeded, g.failed, g.remaining);for await (const task of workly.tasks.list({ groupId: group.id, state: 'failed' })) { console.log(task.id, task.lastError);}The callback’s body is a GroupSummary. It arrives as the task’s payload, so its fields are snake_case: group_id, status, total, succeeded, failed, cancelled.
Callbacks
Section titled “Callbacks”Tasks and schedules take the same onComplete: each time the task, or a run of the schedule, succeeds, fails or is cancelled, Workly POSTs a summary of it to the URL. See Callbacks.
await workly.tasks.enqueue('exports', { url: 'https://api.example.com/jobs/export', payload: { exportId: 42 }, onComplete: { url: 'https://api.example.com/jobs/export-done' },});await workly.schedules.put('nightly-report', { cron: '0 3 * * *', url: 'https://api.example.com/reports/nightly', onComplete: { url: 'https://api.example.com/reports/nightly-done' },});The bodies are a TaskSummary (task_id, queue, state, attempt_count, last_status, last_error, finished_at, …) and a RunSummary (run_id, schedule, state, …), in snake_case as sent.
Workflows
Section titled “Workflows”A workflow is a DAG of HTTP steps: each step is delivered as a task once the steps in its dependsOn have succeeded, and a failed step stops the run. Most workflows live in a workly.yaml and are applied with workly deploy; put does the same from code, declaratively. See Workflows.
await workly.workflows.put('daily-refresh', { steps: [ { name: 'prices', url: 'https://api.example.com/jobs/prices' }, { name: 'fx', url: 'https://api.example.com/jobs/fx' }, { name: 'analytics', url: 'https://api.example.com/jobs/analytics', dependsOn: ['prices', 'fx'] }, ],});
const started = await workly.workflows.trigger('daily-refresh', { input: { date: '2026-11-13' }, idempotencyKey: 'refresh-2026-11-13',});const run = await workly.workflowRuns.get(started.id);for (const step of run.steps) console.log(step.name, step.status, step.blockedBy, step.error);
for await (const failed of workly.workflowRuns.list({ workflow: 'daily-refresh', status: 'failed' })) { await workly.workflowRuns.retry(failed.id); // its failed and skipped steps run again}await workly.workflowRuns.cancel(run.id); // steps not yet started are skippedA step without payload or body is sent the run’s context as JSON, with input. A step can also wait for a task group: its endpoint answers 2xx with Workly-Wait-For: group/<id>, and the step finishes when the group does.
Alerts
Section titled “Alerts”Alert channels get an email or a Slack message when tasks or schedule runs fail: within about a minute, then at most one every 30 minutes per queue or schedule. See Alerts.
const channel = await workly.alerts.create('slack', 'https://hooks.slack.com/services/...'); // or 'email', 'ops@example.com'await workly.alerts.test(channel.id); // send a test alert nowconsole.log((await workly.alerts.list()).channels);await workly.alerts.delete(channel.id);Errors
Section titled “Errors”| Error | When |
|---|---|
BadRequestError |
400, invalid request |
AuthenticationError |
401, missing or wrong API key |
PermissionDeniedError |
403, not allowed, or a hosted limit was reached (e.g. quota_exceeded) |
NotFoundError |
404, no such queue or task |
ConflictError |
409, e.g. retrying a running task |
PayloadTooLargeError |
413 |
RateLimitError |
429, still rate limited after the retries |
APIError |
base class of the above; has .status, .code (stable) and .message |
APIConnectionError |
the server couldn’t be reached, or the request timed out |
All of them extend WorklyError. Requests are retried up to maxRetries times (2 by default), honouring Retry-After. A 429 is always retried, since the server refused the request without doing anything. Connection errors and 502–504 are retried for requests that are safe to repeat: an enqueue only when it has an idempotencyKey, or when the connection failed before the request was sent.
Options
Section titled “Options”const workly = new Workly({ url: 'https://workly.internal', // default WORKLY_URL, then http://localhost:7337 apiKey: '...', // default WORKLY_API_KEY timeoutMs: 30_000, // per call, including retries maxRetries: 2, fetch: customFetch,});
// Every method takes an AbortSignal last.await workly.tasks.get(id, { signal: AbortSignal.timeout(1000) });