SDKs
TypeScript / JavaScript — @justcrawl/sdk
Section titled “TypeScript / JavaScript — @justcrawl/sdk”The official client. Zero runtime dependencies, Node 20.3+, ESM and CommonJS, Apache-2.0, published with npm provenance.
npm install @justcrawl/sdk- npm:
@justcrawl/sdk - Source: github.com/justcrawl-io/justcrawl-sdk-js
Its types are generated from the same OpenAPI spec that powers this site, and a CI gate fails our build if the two ever disagree — so the SDK cannot drift from the API.
Provider discovery and workflow creation use Bright Data, Oxylabs, Nimble Way and Zyte. Past jobs and workflow versions keep their original provider labels. See retired providers for admission and account recovery.
Client
Section titled “Client”import { JustCrawl } from '@justcrawl/sdk';
const jc = new JustCrawl({ apiKey: process.env.JUSTCRAWL_API_KEY!, // sr_live_… baseUrl: 'https://api.justcrawl.io', // default timeoutMs: 30_000, // default maxRetries: 2, // default; safe reads + keyed BatchJob/BI submit});Your API key is stored non-enumerably and masked in toJSON() and
console.log, so it does not end up in logs, crash reports, or serialized
state.
Listing, creating and revoking API keys requires org:manage (Owner and Admin
by default); existing keys use their creator’s current role grants.
plans.status() remains available to authenticated org members. Credit history,
recharge status and recharge submission require org:manage and return HTTP 403
when the caller lacks it.
List sorting and filtering
Section titled “List sorting and filtering”Use each list’s optional ordering and filters to walk a result set. For example, request failed Jobs in descending update order.
const jobs = await jc.jobs.list({ status: 'failed', sort: 'updated', order: 'desc' });For batch lists, keep the filters and sort settings when reusing a cursor. The list options are typed from the API reference.
Resources
Section titled “Resources”One group per API area:
| Group | Covers |
|---|---|
jobs |
submit, list, poll, batch status, results |
batchJobs |
definition create/list/get/update, count and start |
batchInputs |
durable input create/metadata/append/seal |
batchJobRuns |
history, exact-key recovery, summary, jobs, results and discoveries |
urls |
URL items, batch create/delete, per-URL jobs and extractions |
workflows |
create, validate, publish, clone, versions, routing |
smartWorkflows |
auto-optimization mode and routing suggestions |
schedules |
recurring crawls, runs, toggle, manual trigger |
extraction |
results, schemas, custom attributes, XPath testing, backfill |
analytics |
overview, timeseries, providers, domains, matrix |
benchmarks |
provider benchmark runs and results |
plans |
plan status, credit ledger, recharge requests |
integrations |
SQS inputs, S3/webhook outputs, storage config |
webhooks |
public URL ingestion |
bi |
SQL console: schema, queries, saved queries, exports |
Anything without a wrapper — authentication, account, and audit-log endpoints included — is reachable through the typed escape hatch:
const me = await jc.request('get', '/api/v1/auth/me');const job = await jc.request('get', '/api/v1/jobs/{id}', { path: { id: jobId } });request() is typed against the generated spec, so an unknown path, an
unsupported method, or a missing path parameter is a compile error. Paths are
the spec’s own templates and the values go in path; interpolating them into
the string yourself produces a plain string, which nothing can check.
For an endpoint published after your installed version was cut, opt out of the checking explicitly:
const preview = await jc.requestUnchecked<{ ok: boolean }>('get', '/api/v1/preview/thing');Extraction results and history
Section titled “Extraction results and history”Call extraction.getResultByJob(jobId) and check its status. An available
result contains the latest revision. pending includes retry timing, and
no_extraction is final for a scrape-only job. A result_lost error is final.
A 503 results_unavailable response uses the SDK’s transient retry policy.
Use extraction.getRawResult(jobId) for the raw extracted JSON download
target. Use urls.listExtractions(urlItemId, { cursor }) with the preceding
response’s nextCursor for URL history. For re-extraction, pass
{ jobIds: [jobId] } to extraction.backfill and use the returned replay job
IDs to follow queued work.
BatchJob lifecycle
Section titled “BatchJob lifecycle”The SDK has 15 BatchJob methods, all typed from the public OpenAPI contract:
| Resource | Methods |
|---|---|
batchJobs |
create, list, get, update, count, start |
batchInputs |
create, get, append, seal |
batchJobRuns |
list, get, jobs, results, discoveries |
Upload and seal durable input, then count before launching:
const entries = ['https://example.com/product/1', 'https://example.com/product/2'];const input = await jc.batchInputs.create();const receipt = await jc.batchInputs.append(input.id, { ordinal: 0, entries });console.log(receipt.acceptedCount, receipt.rejectedOrdinals);await jc.batchInputs.seal(input.id, { chunkCount: 1, entryCount: entries.length });
const count = await jc.batchJobs.count({ inputId: input.id });console.log(count.count, count.largeRun, count.warningThreshold);// Show this count and obtain confirmation for a large run before continuing.
const submissionKey = crypto.randomUUID(); // persist before sendingconst run = await jc.batchJobs.start( { source: { inputId: input.id, workflowId: null }, maxJobs: 100 }, { idempotencyKey: submissionKey },);console.log(run.id, run.entryMode, run.submissionKey, run.phase);workflowId: null uses Automatic routing; configure published routes before
launching. Start returns HTTP 202 with durable identity, replayed and the
current summary before jobs exist. It does not poll for completion. A sealed-input
quick start creates a hidden definition. Reusable definitions own their workflow,
input and discovery policy; start accepts source: { definitionId } without
overriding them. Definition saves return the saved definition and nonblocking
selector-overlap/inheritance warning codes.
Count accepts exactly one of definitionId, sealed inputId or tags. Encode
a tag array as tags: JSON.stringify(tags); empty tags select every enabled URL.
Show count before starting and use the returned
largeRun and warningThreshold to confirm a large launch first. Unavailable or
forbidden counts do not mean zero. Work spends your organization’s credits behind
quota checks and the refund policy, may take hours and has no customer
cancellation. There is no platform size cap; optional maxJobs is your chosen
positive safe-integer admission cap. Reaching it yields max_jobs and a partial
outcome. Later discovery may grow beyond the initial count.
REST/SDK chunks contain at most 1,000 entries and 256 KiB serialized UTF-8,
including the inputId, ordinal and entries envelope. Keep the input ID,
zero-based ordinals and exact chunk contents for replay. Receipts retain rejected
ordinals; rejected entries still count toward the submitted total when sealing.
Seal verifies contiguous chunks and declared totals. batchInputs.get returns
bounded metadata, not every URL. MCP appends have the tighter 100-entry limit.
Continue run pages without starting another run:
const first = await jc.batchJobRuns.jobs(run.id, { limit: 50 });const next = first.pageInfo.nextCursor ? await jc.batchJobRuns.jobs(run.id, { limit: 50, cursor: first.pageInfo.nextCursor }) : null;Pages use items, pageInfo: { nextCursor, hasMore } and each entry’s
cursorAfter; limits default to 50 and cap at 100. Keep filters unchanged while
continuing. A fresh traversal finds later results, descendants and discoveries;
existing cursors do not freeze mutable statuses or late commits. Preparing values
can be null, draining can include output, and seed/descendant counters remain
separate. Use phase/outcome to determine completion rather than an empty page.
Job references support workflows without extraction; result rows retain identity
and explicit availability or an oversized-data omission. Refund withholding
precedes expiry. Fetch a platform download link without an API key.
Recover an uncertain BatchJob start
Section titled “Recover an uncertain BatchJob start”import { BatchJobSubmissionIndeterminateError } from '@justcrawl/sdk';
try { await jc.batchJobs.start(intent, { idempotencyKey: submissionKey });} catch (error) { if (!(error instanceof BatchJobSubmissionIndeterminateError)) throw error; const recovered = await jc.batchJobRuns.list({ submissionKey: error.submissionKey, entryMode: error.entryMode, }); console.log(recovered.items[0] ?? 'No acceptance committed; repeat the same intent with the same key.');}The error carries submissionKey, entryMode: 'api',
operation: 'batchJobs.start', source and dispatched: true. It preserves
recovery after network/timeout exhaustion, abort after send, exhausted possibly
accepted server failures, or success without a usable run handle. An abort before
send remains a JustCrawlAbortError with dispatched: false. Definitive
validation, conflict and quota responses retain normal typed errors when no
earlier attempt was ambiguous. An earlier lost response, timeout or possibly
accepted server failure preserves the recovery key even if a later attempt gets
401/403, 402 or conflict. The indeterminate error retains the final HTTP cause;
restore authentication or permissions when needed, then recover the original key.
Exact recovery accepts a 1–256-character key, including non-UUID strings, and returns zero or one full run independently of recent history. Do not combine it with a cursor, limit or other filters. Zero matches means acceptance did not commit: repeat the same intent with the same key. Keep the key and normalized intent before sending; changed intent under an accepted key conflicts. A new key is for a deliberate new invocation. An abort does not cancel an accepted run.
BatchJob submission uses this SDK error; BI keeps its existing errors and the MCP BI tools retain their own submission key for exact history recovery. The in-site Agent Playground does not start BatchJobs yet.
See Batch jobs for reusable definitions, discovery tags and MCP continuation.
Structured and saved BI queries
Section titled “Structured and saved BI queries”New structured analysis sends a bounded aggregate definition, never SQL:
const query = await jc.bi.runStructuredQuery({ definition: { version: 1, table: 'flat__shop__product', dimensions: [{ kind: 'time_bucket', column: 'captured_at', granularity: 'day' }], measures: [{ function: 'average', column: 'price' }], limit: 100, },});
// Wait for jc.bi.getQuery(query.jobId) to report success before saving.const { savedQuery } = await jc.bi.createSavedQuery({ name: 'Daily shop price', sourceQueryId: query.jobId,});const replay = await jc.bi.runSavedQuery(savedQuery.id);The source save copies the completed execution’s content, immutable org/agent
scope, dialect, and provenance on the server. Do not send scope fields or copy
sqlPreview back as executable input. runSavedQuery likewise sends only the
saved id. To edit a structured saved object in SQL, call
convertSavedQueryToSql(id); conversion does not mutate it, and a later
updateSavedQuery preserves scope and records the clickhouse dialect.
Legacy PostgreSQL SQL must be rewritten before it can run on ClickHouse.
BI result exports
Section titled “BI result exports”Export a completed result without rerunning it. Create once, retain the export handle, and poll it; each ready response contains a fresh download link.
const { export: started } = await jc.bi.createExport(query.jobId, { format: 'parquet',});const { export: current } = await jc.bi.getExport(started.id);
if (current.status === 'ready' && current.downloadUrl) { const response = await fetch(current.downloadUrl); // no Authorization header const bytes = await response.arrayBuffer();}Creation requires bi:write; polling requires bi:read. The default admission
limits are 100,000 rows and 256 MiB of stored source JSONL. Recovery has a
finite attempt budget, and terminal failures retain both the query and export
IDs. Fetch the download link directly without the JustCrawl API key. CSV exports
neutralize formula-like headers and cells with a leading apostrophe before CSV
escaping; choose Parquet when exact values must round-trip without that safety
prefix. Result pages expose the server-derived exportEligibility decision,
including caller permission and both admission-cap checks.
Waiting for jobs
Section titled “Waiting for jobs”const job = await jc.jobs.submitAndWait( { urlItemId }, { maxWaitMs: 120_000, signal: controller.signal, onPoll: (j) => console.log(j.status) },);Polling in chunks with exponential backoff — there is no streaming interface,
because the API exposes none. submitAndWait resolves on both completed
and failed; check job.status.
Creating URLs and schedules
Section titled “Creating URLs and schedules”The SDK exposes the published request shapes directly. The single-URL handler
currently consumes url and optional priority; do not send tags on this
endpoint. Schedule creation can use a published workflow or Automatic routing,
and enablement is explicit desired state:
const target = await jc.urls.create({ url: 'https://example.com/products/123', priority: 10,});
const count = await jc.batchJobs.count({ tags: JSON.stringify([]) });console.log(count.count, count.largeRun, count.warningThreshold);// Show the count and obtain confirmation before enabling large recurring work.const schedule = await jc.schedules.create({ name: 'Six-hour product sweep', workflowId: null, // Automatic routing per URL frequency: 'every_6_hours', timezone: 'UTC', tagFilters: [], // every enabled URL in the organization isEnabled: false, // configure first; enable when ready});
await jc.schedules.toggle(schedule.id, { isEnabled: true });URL creation requires urls:write. Schedule creation and enable/disable require
schedules:write plus a verified account email. Every lookup and mutation is
scoped to the API key’s organization. Repeating either write is not treated as
idempotent: ordinary POST and PATCH calls are never retried by the SDK.
Manual triggering has its own replay-safe contract:
const submissionKey = crypto.randomUUID(); // retain with the normalized intentconst run = await jc.schedules.trigger(schedule.id, { maxJobs: 500 }, { idempotencyKey: submissionKey });console.log(run.id, run.replayed, run.outcome, run.skipReason);const recovered = await jc.batchJobRuns.list({ submissionKey, entryMode: 'schedule_run_now' });const history = await jc.schedules.listRuns({ runId: run.id });Trigger returns a 202 run summary before jobs exist. It can accept, replay or
record a terminal skip. Overlap skips retain blockingRunId and
blockingRunAgeSeconds; unresolved workflows use skipReason: 'workflow_unresolved'. A skip consumes its key, so a deliberate new trigger
after the blocker settles needs a new key. Uncertain submissions throw the same
BatchJobSubmissionIndeterminateError as BatchJob start, with operation: 'schedules.trigger', entryMode: 'schedule_run_now' and source: { scheduleId }.
Recover before choosing a new key; zero matches permits the same intent/key.
Changing maxJobs under a used key conflicts. See Schedules.
Schedule history merges new accepted/skipped runs and legacy rows newest first.
New rows have kind: 'batch', runId, phase/outcome and skip metadata. Legacy
rows have kind: 'legacy', frozen counts and no run link. Accepted runs, jobs and
receipts survive ordinary schedule deletion. The run keeps its frozen
scheduleName while the deleted scheduleId becomes null.
Results
Section titled “Results”const result = await jc.jobs.fetchResult(jobId);
switch (result.kind) { case 'url': return result.data; // downloaded for you case 'blob': return result.blobKey; // your bucket — fetch with your own creds case 'expired': return result.expiredAt; // aged out of your retention window case 'refunded': return result.message; // no provider delivered a page; the job was free}expired and refunded are outcomes, not exceptions — neither is a fault on
your side, so neither throws. They mean different things: expired is a page
that existed and was swept by your retention policy, refunded is a page that
was never delivered at all, so the job’s credit came back and no retry of the
fetch will ever produce a body. The job resource says the same thing in its
creditOutcome / creditNote fields.
The SDK fetches the link without an Authorization header. The gateway checks the issuing credential and current access to the result. Revocation can also interrupt an active download.
Errors
Section titled “Errors”import { JustCrawlError } from '@justcrawl/sdk';
try { await jc.jobs.submit({ urlItemId });} catch (err) { if (err instanceof JustCrawlError) { err.status; // HTTP status err.code; // machine-readable code err.inferredCode; // true when the SDK derived the code from the status err.requestId; // quote this in support requests err.raw; // the untouched response body }}inferredCode is worth understanding: not every endpoint sends a machine code
yet. When one doesn’t, the SDK derives a sensible code from the HTTP status and
sets this flag — it never presents a guess as something we said. Branch on
err.code only after checking it, or branch on err.status.
Recover a lost BI submission
Section titled “Recover a lost BI submission”Keep your own UUID in the Idempotency-Key header when you need to recover
from a lost response after all SDK retries. Then use
jc.bi.listQueries({ submissionKey }) to find the retained handle without
submitting again. This exact lookup is tenant-scoped and remains available
after newer queries fill recent history; a missing key returns an empty list.
Retries
Section titled “Retries”GET requests retry on network errors, 5xx, and 429, honoring Retry-After
when present and falling back to exponential backoff with jitter when it isn’t.
jobs.fetchResult() applies the same policy to the result download link, and
replaces an expired link once by reading the result pointer again.
Ordinary writes are never retried. Submitting a job twice charges two
credits. batchJobs.start(), schedules.trigger(), bi.runQuery(), bi.runStructuredQuery(), and
bi.runSavedQuery() are the endpoint-specific exceptions. The SDK generates a
UUID when omitted, preserves a caller-supplied key and reuses it for every
attempt, so a lost response resolves to the original handle. BatchJob replay
returns its original run summary; its key accepts 1–256 characters while BI
requires a UUID. Schedule trigger uses the same 1–256-character key contract as
BatchJob start and recovers in schedule_run_now. Definition/input writes and
schedule create/update/toggle/delete do not gain retries. A crawl that fails at every provider has its credit returned
automatically, but a retried submit that succeeds is a second real charge, so
the refund is no substitute for the dedup pattern. 402 Insufficient credits
is never retried either — it needs a human to add credits, not another request.
Other languages
Section titled “Other languages”There is no first-class SDK for other languages yet. The API is plain REST with bearer auth, and our OpenAPI spec is published — most generators produce a workable client from it directly.
If you’re writing your own client, three rules are worth copying from ours:
- Do not retry ordinary writes. A retried
POST /jobscharges twice. BI query submission, saved-query replay and BatchJob start are the exceptions, and only when every attempt reuses the same intent andIdempotency-Key. BatchJob keys accept 1–256 characters; BI keys must be UUIDs. - Retry
429and honorRetry-Afteron safe methods. - Fetch
resultUrlwithout an API key. The URL contains its own private download ticket.
Model Context Protocol — @justcrawl/mcp-server
Section titled “Model Context Protocol — @justcrawl/mcp-server”If you want an agent to use justcrawl rather than your code, reach for the MCP server instead of this SDK. It is a local stdio process your agent host spawns, and it exposes thirty-six tools over the same API — a guided scrape that builds the routing workflow for you, raw job submission and inspection, browsing workflows, seven consolidated BatchJob lifecycle tools, creating and browsing schedules and URLs, discovering the authorized BI catalog, running safe structured or saved BI queries, creating and polling CSV/Parquet exports, and searching these docs.
{ "mcpServers": { "justcrawl": { "command": "npx", "args": ["-y", "@justcrawl/mcp-server"], "env": { "JUSTCRAWL_API_KEY": "sr_live_your_key_here" } } }}- npm:
@justcrawl/mcp-server - Setup, per host: Agents & MCP — Claude Desktop, Cursor, Codex CLI
- Capability policy: every SDK resource method mapped or explicitly omitted
It is built on this SDK, so the three rules above hold there too; the server
inherits them rather than reimplementing them. One rule is its own: it rejects
any sql argument on any tool. jc_bi_query accepts only structured aggregate
intent, jc_bi_save_query can save a completed structured run, and new
jc_bi_run_saved calls take the id of either an MCP-created or dashboard-created
saved query. Its optional queryId continuation alias remains only until the
next MCP npm major; jc_bi_get_results is the supported continuation tool and resumes either returned query
handle without resubmitting it. jc_bi_create_export and jc_bi_get_export
preserve one export handle through finite recovery and return the fresh storage
URL without fetching it. A prompt injection hidden in a scraped page therefore
cannot turn into a query over your data or receive your API credential through
an object-store request.
Bound definitions
Section titled “Bound definitions”batchJobs.list({ kind: 'schedule' }) and batchJobs.list({ kind: 'dataset' })
filter bound definitions; omit kind to include every visible kind. Schedule
updates also need schedules:write and verified email. Dataset updates accept
name only, and dataset starts use the server’s stored exact version after
checking the live binding. See definition kinds.