/scraperapi:scraperapi-nodejs-sdkfrom ScraperAPI
Best-practices reference for the ScraperAPI Node.js/JavaScript SDK. Covers CommonJS/ESM imports, async/await, request parameters, POST/PUT, error handling, and credit costs.
Ships in ScraperAPI. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Requires: Node.js 18+ (the snippets use the global fetch), npm install scraperapi-sdk, a ScraperAPI API key.
// CommonJS
const scraperapiClient = require('scraperapi-sdk')('YOUR_API_KEY');
// ES Modules / TypeScript — the default export is a factory function, not a class
import scraperapi from 'scraperapi-sdk';
const scraperapiClient = scraperapi('YOUR_API_KEY');
The package ships type definitions in dist/ but doesn't declare them in package.json, so TypeScript reports a missing declaration file. Add declare module 'scraperapi-sdk'; to a .d.ts file in your project, or set noImplicitAny: false.
Replace YOUR_API_KEY with your key from https://dashboard.scraperapi.com. Never commit a real key to source control.
| Situation | Pattern |
|---|---|
| Single URL, result needed now | scraperapiClient.get(url) |
| 20+ URLs or batch work | Async Jobs API — fetch/axios to async.scraperapi.com/jobs |
| Supported platform (Amazon, Google, Walmart, eBay, Redfin) | Structured Data endpoint — api.scraperapi.com/structured/<vertical> |
| Page loads content via JavaScript | .get(url, { render: true }) |
| Site blocks datacenter proxies | .get(url, { premium: true }) |
| Need to POST a form or JSON body to the target | .post(url, options) |
// GET — resolves to { body, headers, statusCode }, not a string
const res = await scraperapiClient.get('https://example.com/');
if (res.statusCode === 200) console.log(res.body);
// With parameters
const res = await scraperapiClient.get('https://example.com/', {
render: true,
country_code: 'us',
});
// Without async/await (Promise chain)
scraperapiClient.get('https://example.com/')
.then(res => console.log(res.statusCode, res.body))
.catch(err => console.error(err)); // network errors only, see Error Handling
Every method (get, post, put) resolves even when ScraperAPI returns 401, 403, 429 or 500, so always check res.statusCode before using res.body.
// POST — forward a JSON body to the target site
const res = await scraperapiClient.post('https://example.com/api', {
body: JSON.stringify({ query: 'example' }),
headers: { 'Content-Type': 'application/json' },
});
// PUT — same signature, different HTTP method
const res = await scraperapiClient.put('https://example.com/resource', {
body: JSON.stringify({ name: 'updated' }),
headers: { 'Content-Type': 'application/json' },
});
// Render JavaScript before returning HTML
// Use when: page uses React/Vue/Angular, or initial scrape returns empty content
// Cost: 10 credits per request (instead of 1)
const res = await scraperapiClient.get('https://spa-site.com/', { render: true });
// Wait for a specific element before capturing (requires render: true)
const res = await scraperapiClient.get('https://spa-site.com/', {
render: true,
wait_for_selector: '.product-list',
});
// Screenshot (auto-enables rendering)
const res = await scraperapiClient.get('https://example.com/', { screenshot: true });
Start without render: true. Add it only when the response is missing expected content.
// Route through a specific country — no extra credit cost
const res = await scraperapiClient.get('https://example.com/', { country_code: 'gb' });
// Premium residential/mobile proxies
// Cost: 10 credits (25 with render: true)
const res = await scraperapiClient.get('https://hard-site.com/', { premium: true });
// Ultra-premium — for the toughest anti-bot protections
// Cost: 30 credits (75 with render: true)
// Incompatible with custom headers — keep_headers is ignored when ultra_premium is set
const res = await scraperapiClient.get('https://hardest-site.com/', { ultra_premium: true });
premium and ultra_premium are mutually exclusive — never set both.
Escalation order: standard (1 cr) → render (10 cr) → premium (10 cr) → premium+render (25 cr) → ultra_premium (30 cr).
// Reuse the same proxy IP across requests (same session_number = same IP)
// Sessions expire 15 minutes after last use
const page1 = await scraperapiClient.get('https://example.com/page1', { session_number: 42 });
const page2 = await scraperapiClient.get('https://example.com/page2', { session_number: 42 });
session_number can't be combined with premium or ultra_premium.
// Forward your own headers to the target site
// Note: keep_headers is ignored when ultra_premium: true
const res = await scraperapiClient.get('https://example.com/', {
keep_headers: true,
headers: { 'Accept-Language': 'en-US', 'Referer': 'https://google.com' },
});
// Emulate mobile or desktop browser
const res = await scraperapiClient.get('https://example.com/', { device_type: 'mobile' });
// Structured JSON for supported sites (Amazon, Google, etc.)
const res = await scraperapiClient.get('https://amazon.com/dp/B09V3KXJPB', { autoparse: true });
// Markdown — useful for LLM pipelines or documentation tools
const res = await scraperapiClient.get('https://docs.example.com/', { output_format: 'markdown' });
// Plain text
const res = await scraperapiClient.get('https://example.com/', { output_format: 'text' });
// Returns usage stats: concurrent request usage, total requests, account limits
const account = await scraperapiClient.account();
console.log(account);
Use this to monitor credit consumption and concurrency limits programmatically.
async function scrapeWithEscalation(url) {
const tiers = [
{}, // 1 credit
{ render: true }, // 10 credits
{ premium: true }, // 10 credits
{ premium: true, render: true }, // 25 credits
{ ultra_premium: true }, // 30 credits
];
for (const params of tiers) {
const res = await scraperapiClient.get(url, params);
// bad key, out of credits or max_cost hit: a pricier tier won't help
if (res.statusCode === 401 || res.statusCode === 403) throw new Error(`ScraperAPI ${res.statusCode}: ${res.body}`);
if (res.statusCode === 200 && res.body.includes('<html')) return res.body;
}
return null;
}
Credits above are for a normal site; Google, Amazon and bot-protected sites cost more (see Credit Cost Reference).
The sync SDK waits on each call and sets no timeout of its own. For 20+ URLs, use the async endpoint directly to fan out jobs.
const API_KEY = 'YOUR_API_KEY';
async function submitJob(url, apiParams = {}) {
const res = await fetch('https://async.scraperapi.com/jobs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// without expectUnsuccessReport, a job that fails never reaches "failed"
body: JSON.stringify({ apiKey: API_KEY, url, apiParams, expectUnsuccessReport: true }),
});
return res.json(); // { id, status, statusUrl }
}
// Jobs can keep retrying for up to 24h; pick a deadline that fits your use case
async function pollJob(job, maxWaitMs = 600_000, intervalMs = 10_000) {
const deadline = Date.now() + maxWaitMs;
while (Date.now() < deadline) {
const res = await fetch(job.statusUrl);
const data = await res.json();
if (data.status === 'finished') return data.response.body;
if (data.status === 'failed') throw new Error(`Job ${job.id} failed`);
await new Promise(r => setTimeout(r, intervalMs));
}
throw new Error(`Job ${job.id} timed out`);
}
// Batch — submit all, then collect; allSettled so one failed job doesn't lose the rest
const urls = ['https://example.com/p1', 'https://example.com/p2'];
const jobs = await Promise.all(urls.map(u => submitJob(u)));
const results = await Promise.allSettled(jobs.map(j => pollJob(j)));
For supported platforms, use structured endpoints instead of raw HTML — they return clean JSON without parsing logic.
async function structuredGet(vertical, params) {
const query = new URLSearchParams({ api_key: API_KEY, ...params });
const res = await fetch(`https://api.scraperapi.com/structured/${vertical}?${query}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
// Google SERP
const serp = await structuredGet('google/search', { query: 'javascript scraping' });
// Amazon product
const product = await structuredGet('amazon/product', { asin: 'B09V3KXJPB' });
// Walmart search
const items = await structuredGet('walmart/search', { query: 'standing desk' });
See structured data docs for all verticals and required fields.
The SDK only rejects on network errors (DNS, connection reset). HTTP errors from ScraperAPI resolve normally, so read statusCode. It also sets no timeout; ScraperAPI can take up to 70s, so cap the wait yourself.
const withTimeout = (p, ms = 75_000) =>
Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('Timed out')), ms))]);
async function safeScrape(url, params = {}) {
const res = await withTimeout(scraperapiClient.get(url, params)); // rejects on network error or timeout
const { statusCode, body } = res;
if (statusCode === 200 || statusCode === 404) return res; // 404 is the target's answer (charged)
if (statusCode === 401) throw new Error('Invalid API key — check your API key');
if (statusCode === 403) throw new Error("Out of credits or over max_cost — check https://dashboard.scraperapi.com/billing (don't retry)");
if (statusCode === 429) throw new Error('Rate limit — reduce concurrency or switch to async');
if (statusCode === 500) throw new Error('Failed after ScraperAPI retried for 70s (not charged) — retry; on protected sites add premium or ultra_premium');
throw new Error(`ScraperAPI ${statusCode}: ${body.slice(0, 200)}`);
}
Promise.race stops waiting but doesn't cancel the underlying request.
Status codes: 200 success, 400 malformed request, 401 bad key, 403 credits exhausted or max_cost exceeded (don't retry), 404 not found (target, charged),
429 concurrency limit, 500 failed after 70s of retries (not charged — retry, then escalate to premium/ultra_premium on protected sites).
| Request type | Credits |
|---|---|
| Standard | 1 |
render: true | 10 |
premium: true | 10 |
premium: true + render: true | 25 |
ultra_premium: true | 30 |
ultra_premium: true + render: true | 75 |
Those are the costs on a normal site. Some sites cost more per request:
| Site | Credits |
|---|---|
| Amazon, Walmart, eBay | 5 |
| Google, Bing (all subdomains) | 25 |
| 30 | |
| Sites behind Cloudflare, DataDome, PerimeterX or Akamai | 10 |
Combined costs vary by site; check the exact price with /account/urlcost or the sa-credit-cost header before a large run. Add max_cost: N to any request's options to cap what it can spend (ScraperAPI returns 403 instead).
You're charged for 200 and 404 responses, and for requests you cancel before ScraperAPI's 70s
of retries finish. Each response's sa-credit-cost header shows what it cost; preview a cost
without spending credits with GET https://api.scraperapi.com/account/urlcost?api_key=...&url=...
(it accepts the same parameters). Source: https://docs.scraperapi.com/getting-started/quick-start/credits-and-requests-costs
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub scraperapi/scraperapi-skills --plugin scraperapi20 skills in this plugin
/scraperapi-agent-onboardingEntry point for agents and developers new to ScraperAPI. Read first when integrating ScraperAPI into an agent or app, setting up the MCP server for Claude Code or other LLM tools, choosing the right ScraperAPI product, or getting an API key. Trigger on: "how do I use ScraperAPI", "set up ScraperAPI", "connect ScraperAPI to Claude", "which ScraperAPI product should I use", "get web data for my agent", "add web scraping to my project", "ScraperAPI getting started". After reading, route to the narrower skill that owns the chosen path. If the user already named a language or SDK, n8n, Zapier, or the sapi CLI, use that skill directly instead.
Note: Transmits user-supplied queries, URLs, and content to ScraperAPI.
/scraperapi-asyncReference for ScraperAPI's Async Jobs REST API: submit scraping jobs in the background and get results by polling or webhook, including batch jobs. Consult when the user is scraping many URLs, needs non-blocking requests, or wants webhook delivery. Use when user asks: "how do I scrape 1000 URLs with ScraperAPI", "ScraperAPI async jobs", "batch scraping with ScraperAPI", "submit a scraping job and poll for results", "ScraperAPI webhook callback", "ScraperAPI batchjobs endpoint". Covers single and batch jobs, webhook callbacks, apiParams, async-only parameters, binary responses, retention, and error handling. It is language-agnostic: for SDK client code, use the language's SDK skill; to crawl a whole site by following links, use scraperapi-crawler.
Note: Transmits user-supplied queries, URLs, and content to ScraperAPI.
Other plugins' skills for the same job