Call a web scraping API from Node.js and TypeScript: fetch, typed results and retries
Web scraping API Node.js guide: call it with fetch, type the extracted data from the output schema, retry 429 and 503 safely, watch X-Credit-Balance.
- Published
- Reading time
- 9 min read
- By
- ExtractHub team
- Node.js
- TypeScript
- web scraping API
- error handling
- tutorial
On this page
A Node.js scraper usually starts as fetch plus an HTML parser, and the TypeScript types are whatever the parser happened to return that day. This guide does it the other way round: call a web scraping API from Node.js, get structured JSON back, and give that JSON a real type that stays valid for as long as you pin a major version. You will build a small typed client with fetch, typed results, safe retries on 429 and 503, and a credit check from the response headers.
The examples use the ExtractHub extract API. Every parameter, header and error code below is taken from the API’s code; the API reference has the full list. If you work in Python, the same flow is in calling a web scraping API from Python.
Setup: Node 18+, an API key and a pinned extractor
- Node 18 or later.
fetchandAbortSignal.timeout()are built in; the client below needs no dependency. - An API key from the API keys page. Start with a test key (
exth_test_...): it never fetches a page and never uses credit, so you can write the whole client against it. Switch to a live key (exth_live_...) when it works. - A released extractor, a versioned web scraper that holds the fetch options and the fields to pull out. Build your own with the agent skill or pick a public one in the extractor catalog.
export EXTRACTHUB_API_KEY="exth_test_..."
Keep the key on the server side: a Node.js backend, a serverless function, a cron script. Browser code would expose it to anyone who opens the developer tools, so send only the extracted data to the front end.
The first call: a web scraping API request from Node.js with fetch
The realtime endpoint is GET /api/extractor/extract with two query parameters: target_url (the page) and extractor_id (the extractor with a version pin).
const API_URL = "https://api.extracthub.io";
const API_KEY = process.env.EXTRACTHUB_API_KEY!;
const params = new URLSearchParams({
target_url: "https://www.example.com/p/123",
extractor_id: "@you/example-product@1",
});
const res = await fetch(`${API_URL}/api/extractor/extract?${params}`, {
headers: { "X-API-Key": API_KEY },
signal: AbortSignal.timeout(120_000),
});
const body = await res.json();
console.log(res.status, body.result?.extracted);
URLSearchParams encodes the @ and / of the id. Authorization: Bearer <key> works too; send one of the two headers, because two different keys in both are rejected with 400 ambiguous_credentials.
The pin is required. @you/example-product@1 follows the latest 1.x release, @you/example-product@1.2.0 freezes one version, and @draft runs the unreleased draft (owner only). An unpinned id gets 400 pin_required with the available majors in the message. Pins are what make the typed client below safe: a breaking change never reaches a major pin.
The two-minute timeout is deliberate: a realtime request may wait up to 30 seconds for scraping capacity before the API turns it into an async job, and the page fetch comes on top of that.
Typing the response envelope
A 200 answer is { success: true, result }. The envelope is the same for every extractor, so type it once. These types follow the API’s response schema:
interface ExtractMetadata {
useProxy: boolean;
renderJs: boolean;
url: string;
scrapedAt: string; // ISO 8601
costUsd?: number;
escalated?: boolean; // plain fetch retried with JavaScript rendering
warnings?: { code: string; message: string }[];
}
interface ExtractResult<T> {
extracted: T;
metadata: ExtractMetadata;
rawHtml?: string; // only with return_raw_html=true
sandbox?: true; // test keys
}
interface ApiError {
success: false;
error: string;
errors?: { code: string; message: string; path?: string; fields?: string[]; hint?: string }[];
details?: { code: string };
requestId?: string;
charged?: boolean;
cost?: number;
top_up_url?: string;
}
Errors come in two shapes: request, fetch and billing errors put the code in errors[0].code; version and job answers (pin_required, a yanked version) put it in details.code. One helper reads both:
function errorCode(body: ApiError): string | undefined {
return body.errors?.[0]?.code ?? body.details?.code;
}
Typing the extracted data from the output schema
result.extracted is where TypeScript usually gives up and you write any. You do not have to. Every released version has an output schema, and the extractor’s public page shows it in a “What it returns” table: one row per top-level field, with types such as string, number, boolean, unknown, string[] or object{name,price} (an object, with its keys).
Translate that table into an interface. For an illustrative example extractor whose table reads title: string, price: number, inStock: boolean, images: string[]:
interface Product {
title: string;
price: number | null;
inStock: boolean | null;
images: string[];
}
Two rules decide how strict the type can be:
- Required fields always have a value. A top-level field the owner marked
requiredcannot come back empty: an empty value fails the whole request with 422required_fields_missinginstead. Optional fields can be empty:null,""or[]. Above,titleis the required one; the others allow empty values. The page table does not mark required fields; theget_extractortool of the MCP server returns the full output schema, including therequiredflags. - A major pin keeps the type valid. Removing a field, renaming it, changing its type, or changing whether it is required is always released as a new major version. Pinned to
@1, yourProductinterface stays correct through every 1.x fix and addition; new fields may appear, so do not reject unknown keys.
TypeScript checks nothing at run time, so add a small guard on the fields your code depends on. It turns a broken assumption into a clear error instead of a NaN three functions later:
function isProduct(x: unknown): x is Product {
const p = x as Product;
return typeof p?.title === "string" && (p.price === null || typeof p.price === "number");
}
A schema library does the same job if you already use one; the point is to validate at the boundary.
A typed client with retries
Now put it together. The client returns typed data, logs version and credit headers, and retries only what is free to retry.
const RETRYABLE = new Set([
"rate_limited", "too_many_queued", "queue_timeout",
"no_provider_available", "upstream_error",
]);
class ExtractError extends Error {
constructor(readonly status: number, readonly code: string | undefined, readonly body: ApiError) {
super(`${status} ${code}: ${body.error}`);
}
get charged() { return this.body.charged === true; }
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function extract<T>(
targetUrl: string,
extractorId: string,
maxAttempts = 4,
): Promise<ExtractResult<T>> {
const params = new URLSearchParams({ target_url: targetUrl, extractor_id: extractorId });
for (let attempt = 1; ; attempt++) {
const res = await fetch(`${API_URL}/api/extractor/extract?${params}`, {
headers: { "X-API-Key": API_KEY },
signal: AbortSignal.timeout(120_000),
});
const body = await res.json();
checkHeaders(res.headers);
if (res.status === 200) return body.result as ExtractResult<T>;
if (res.status === 202) return waitForJob<T>(body.result.status_url);
const code = errorCode(body);
const retry = RETRYABLE.has(code ?? "") && body.charged !== true;
if (!retry || attempt >= maxAttempts) throw new ExtractError(res.status, code, body);
const retryAfter = Number(res.headers.get("Retry-After"));
await sleep(retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000);
}
}
Why this retry set:
- 429 is either
rate_limited(your per-minute limit) ortoo_many_queued(too many of your requests already waiting for capacity).too_many_queuedsendsRetry-After; forrate_limitedthe client falls back to its own backoff. - 503 is
queue_timeout(only when you opted out of async jobs, see below), which sendsRetry-After, orno_provider_available. - 502
upstream_errormeans the scraping service failed before it fetched the page.
All of these are free. The charging rule is the one thing to get right in a retry loop: a request that fails after the page was fetched is charged in full, and its error body carries charged: true, cost and a note. A target_error (the target answered 404, say) or a 504 upstream_timeout is a charged failure, and retrying it is a new charge for a page that will probably answer the same way. That is why the loop checks charged and never retries target_error. The full table of codes and what each one costs is in the Python guide.
Branch on codes, never on error text: messages are for people and can change.
Reading X-Credit-Balance and version headers
Live-key answers carry X-Credit-Balance: your balance in USD with four decimals after this request, pending charges included. It is there on successes, on failures, on a 202 (the job’s credit is already held) and on a 402. Test keys never get it.
const LOW_BALANCE_USD = 5; // your threshold, not an API value
function checkHeaders(h: Headers) {
const version = h.get("X-Extractor-Version");
if (h.get("Deprecation")) {
console.warn(`extractor ${version} is deprecated, sunset ${h.get("Sunset")}`,
h.get("X-Deprecation-Message") ?? "");
}
const renamed = h.get("X-Extractor-Id-Renamed");
if (renamed) console.warn(`extractor renamed, use ${renamed}`);
const balance = h.get("X-Credit-Balance");
if (balance !== null && Number(balance) < LOW_BALANCE_USD) {
console.warn(`credit balance low: ${balance} USD`);
}
}
A 402 insufficient_balance is never charged and its body has top_up_url, the billing page that opens the top-up dialog. Log it or put it in your alert so whoever is on call can act on it. Current prices per request tier are on the pricing section.
The 202 path in a few lines
When no capacity becomes free within 30 seconds, the request is not failed: the API answers 202 with job_id, status_url and result_url and runs it as an async job. Poll the status URL until status is completed (the job then carries result, the same object a 200 would have had) or failed / cancelled (it carries error with a code):
async function waitForJob<T>(statusUrl: string, maxWaitMs = 15 * 60_000): Promise<ExtractResult<T>> {
const deadline = Date.now() + maxWaitMs;
while (Date.now() < deadline) {
const res = await fetch(statusUrl, { headers: { "X-API-Key": API_KEY }, signal: AbortSignal.timeout(30_000) });
const job = (await res.json()).result;
if (job.status === "completed") return job.result as ExtractResult<T>;
if (job.status === "failed" || job.status === "cancelled") {
throw new ExtractError(422, job.error?.code, { success: false, error: job.error?.message ?? job.status });
}
await sleep((Number(res.headers.get("Retry-After")) || 10) * 1000);
}
throw new Error(`job still running after ${maxWaitMs} ms: ${statusUrl}`);
}
If your code must answer now (an HTTP handler, say), add async_fallback=false to the query: a request still waiting after 30 seconds then gets 503 queue_timeout with Retry-After, which the retry loop already handles. To skip polling, pass webhook_url and verify the webhook signature on your server.
Many URLs: limit concurrency, or use the Batch API
Promise.all over a few hundred URLs fires them all at once and runs straight into rate_limited and too_many_queued. Keep a small pool instead:
async function extractAll<T>(urls: string[], extractorId: string, concurrency = 4) {
const results: (ExtractResult<T> | ExtractError)[] = new Array(urls.length);
let next = 0;
async function worker() {
while (next < urls.length) {
const i = next++;
try {
results[i] = await extract<T>(urls[i], extractorId);
} catch (e) {
if (!(e instanceof ExtractError)) throw e;
results[i] = e;
}
}
}
await Promise.all(Array.from({ length: concurrency }, worker));
return results;
}
The concurrency of 4 is a starting point, not an API value. Past a few hundred URLs, stop looping in Node and send them to the Batch API in one request: the same pinned extractor and credit rules, retries handled on the server, results as NDJSON pages.
Test every branch with a test key
A test key accepts sandbox_scenario (a live key sending it gets 400), so you can drive each branch of the client without fetching a page or spending credit:
for (const scenario of ["success", "failed", "timeout_to_job", "insufficient_credit"]) {
const params = new URLSearchParams({
target_url: "https://www.example.com/p/123",
extractor_id: "@you/example-product@1",
sandbox_scenario: scenario,
});
const res = await fetch(`${API_URL}/api/extractor/extract?${params}`, { headers: { "X-API-Key": API_KEY } });
const body = await res.json();
console.log(scenario, res.status, body.success ? "ok" : errorCode(body));
}
failed answers 502 upstream_error (your retry path), timeout_to_job answers 202 with a sandbox job (your polling path) and insufficient_credit answers 402. Sandbox results come from the version’s last passing health check, its released sample, or a fixture built from its output schema, so they have the shape your Product type expects.
FAQ
How do I call a web scraping API from Node.js?
Node 18 and later have fetch built in. Send a GET request to /api/extractor/extract with your API key in the X-API-Key header, the page as target_url and a pinned extractor_id such as @you/slug@1; the fields come back under result.extracted.
How do I get TypeScript types for scraped data?
Write them from the extractor's output schema. The extractor page lists every top-level field of result.extracted with its type (string, number, boolean, arrays, objects), and a major version pin guarantees those fields are never removed or retyped.
Should my Node.js client retry a 429 or a 503?
Yes. 429 and 503 answers are not charged, so retrying them costs nothing; wait for the Retry-After header when it is present, else back off yourself. Do not retry an error body with charged: true automatically, because a retry is a new charge.
Can I call the scraping API from the browser?
Not directly: browser code would expose your API key. Call the API from your Node.js backend, a serverless function or a script, and send only the extracted data to the browser.
Related
- Build a job listings scraper: list pages, JobPosting JSON and dedupe by URL: Build a job listings scraper that returns structured JSON: job URLs from list pages, JobPosting fields and ISO dates from each job page, and dedupe by URL.
- Build a price monitoring scraper: product fields, daily runs and change detection: Build a price monitoring scraper: a product extractor with typed prices, daily batch or scheduled runs, a signed webhook and change detection in your code.
- Use ready-made web scrapers instead of writing one: find, check and pin a public extractor: Use ready-made web scrapers instead of writing one: find a public extractor, read its fields, price tier and health, pin a version and call it with your key.
- Agent skill: install the extractor builder skill for Claude Code
- MCP server: connect Claude Code, Cursor or any MCP client
- API reference: realtime extract, async jobs and the Batch API
- Web scraper catalog: public extractors you can call today