The official Node.js/TypeScript client library for the ScrapeBadger API — Twitter, Google, Vinted, and general web scraping.
- Full TypeScript Support - Complete type definitions for all API endpoints
- Modern ESM & CommonJS - Works with both module systems
- Async Iterators - Automatic pagination with
for await...ofsyntax - Resilient Retries - Exponential backoff with colored console warnings
- Typed Exceptions - Distinct error classes for every failure scenario
- Async requests and webhooks - Run any call asynchronously, wait for it or get a signed webhook; idempotent resubmits
- 37+ Twitter endpoints - Tweets, users, lists, communities, trends, geo, real-time streams
- 20 Google product APIs - Search (with optional deferred AI Overview follow-up and result link resolving), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (search + seller offers by barcode or catalog id), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, Local Pack, Shorts, Flights, Products, Ads Transparency Center
- Vinted scraping - Search items, item details, user profiles, brands, colors, markets
- Web scraping - Anti-bot bypass, JS rendering, screenshots, and selector/AI data extraction
npm install scrapebadgeryarn add scrapebadgerpnpm add scrapebadgerimport { ScrapeBadger } from "scrapebadger";
const client = new ScrapeBadger({ apiKey: "your-api-key" });
// Get a tweet
const tweet = await client.twitter.tweets.getById("1234567890");
console.log(`@${tweet.username}: ${tweet.text}`);
// Scrape a website
const result = await client.web.scrape("https://scrapebadger.com", { format: "markdown" });
console.log(result.content);
// Get a user profile
const user = await client.twitter.users.getByUsername("elonmusk");
console.log(`${user.name} has ${user.followers_count.toLocaleString()} followers`);// Pass API key directly
const client = new ScrapeBadger({ apiKey: "sb_live_xxxxxxxxxxxxx" });
// Or use environment variable SCRAPEBADGER_API_KEY
const client = new ScrapeBadger();The etsy, aliexpress, target, asos, and bestbuy clients expose 44 dedicated ecommerce endpoints. These generated methods return response objects; consult the endpoint documentation for response fields, supported filters, pagination and current pricing.
const client = new ScrapeBadger({ apiKey: "your-api-key" });
const etsy = await client.etsy.searchListings({ query: "ceramic mug" });
const aliexpress = await client.aliexpress.searchProducts({ query: "wireless mouse" });
const target = await client.target.searchProducts({ query: "coffee" });
const asos = await client.asos.searchProducts({ query: "shoes", market: "uk" });
const bestbuy = await client.bestbuy.searchProducts({ query: "laptop" });| Client | Endpoints | Documentation |
|---|---|---|
client.etsy |
8 — listing search/detail/reviews, shop profile/listings/reviews, categories, autocomplete | Etsy |
client.aliexpress |
8 — product search/detail/reviews, store profile/products/categories, category navigation, autocomplete | AliExpress |
client.target |
11 — search, category browse/navigation, autocomplete, product detail/reviews/questions/availability, nearby stores/store detail, markets | Target |
client.asos |
7 — product search/detail, stock/prices, category navigation, search filters, autocomplete, markets | ASOS |
client.bestbuy |
10 — search, category browse/navigation, deals, autocomplete, product detail/reviews/questions/availability, markets | Best Buy |
Etsy and AliExpress category navigation is separate from search: their search methods do not offer a category filter. ASOS search follows its upstream semantic matching. Target and Best Buy serve the US market. The linked endpoint references describe further measured limits.
| API | Description | Documentation |
|---|---|---|
| Web Scraping | Scrape any website with JS rendering, anti-bot bypass, screenshots, and selector/AI extraction | Web Scraping Guide |
| 37+ endpoints for tweets, users, lists, communities, trends, and real-time streams | Twitter Guide | |
| 20 products — Search, Maps, News, Hotels, Trends, Jobs, Shopping, Patents, Scholar, Images, Videos, Finance, AI Mode, Lens, Autocomplete, Local, Shorts, Flights, Products, Ads Transparency | Google Guide | |
| Vinted | Search items, get details, user profiles, and reference data across all Vinted markets | Vinted Guide |
| Wallapop | 10 endpoints across 3 markets (es, it, pt) — listing search with Wallapop's own filters (incl. cars: year, km, gearbox, horsepower), listing detail, seller profile/listings/reviews, autocomplete, categories, search filters and filter options, markets | Wallapop Docs |
| Search posts/subreddits/users, subreddit details, post comments, user profiles, wiki pages, trophies | Reddit Guide | |
| GitHub | 2 endpoints — public user and organization profiles (overview with README and contributions, repositories, and user stars tabs) and public repository detail (identity, fork comparison, latest commit and checks, README, root files, languages, latest release, contributors, dependents, funding, community files). E.g. client.github.getRepository("octocat", "Hello-World") |
GitHub Docs |
| User profile/about/related/posts/videos/reels/tagged/pinned/followers/following/stories/highlights, media detail/comments/replies/likers/oEmbed, search (users/hashtags/places/top/reels/music/autocomplete), hashtag/location/audio feeds | Instagram Guide | |
| Amazon | 14 endpoints — search, autocomplete, product detail, offers, reviews, bestsellers, new releases, deals, category browse, seller profile/products/feedback, markets, categories | Amazon Guide |
| Shopee | 6 endpoints across 11 markets (sg, my, ph, id, vn, th, tw, br, co, cl, mx) — product search, category items, product detail, reviews, category tree, markets | Shopee Guide |
| TikTok | 26 endpoints — user profile/videos/followers/following/liked/reposts, video detail/comments/replies/related/transcript, oEmbed, hashtag detail/videos, music detail/videos, search (general/videos/users/hashtags), trending (videos/hashtags/songs), ad library, regions | TikTok Guide |
| eBay | 12 endpoints across 18 markets — search, search by image, completed/sold listings, item detail, item reviews, seller profile/items/feedback, category browse, categories, autocomplete, markets | eBay Guide |
| Walmart | 11 endpoints (walmart.com, US-only) — search, category browse, deals feed, autocomplete, product detail, reviews, seller profile/products, store detail with nearby stores, markets | |
| Gumtree | 9 endpoints across gumtree.com, gumtree.com.au and gumtree.co.za (market: "uk" default, "au", "za") — search (category, location/postcode radius, price, seller type, urgent/photos, category-specific filters), search filters with live counts, listing detail (full vehicle spec, seller rating/verification, masked phone), seller listings, keyword and location autocomplete, location and category trees, markets. E.g. client.gumtree.search({ market: "au", category: "18320", location: "3003435", distance: 10 }) or client.gumtree.search({ market: "za", category: "p6dnh", location: "dkp8y" }) (za ids are refs) |
Gumtree Docs |
| AutoScout24 | 4 endpoints — search, listing detail (URL or UUID), filters, markets | AutoScout24 Docs |
| Yelp | 2 endpoints — business search (location, query, category alias, sort, price, 8 feature refinements, pages 1–11, ads separate) and markets (us, ca). E.g. client.yelp.searchBusinesses({ location: "San Francisco, CA", query: "pizza" }) |
Yelp Docs |
| Bing | 6 endpoints — web search (with ads + related searches), image search, video search, news vertical, autocomplete, markets | |
| DuckDuckGo | 7 endpoints — web search (with instant-answer abstract), image search, news vertical, video search, autocomplete, instant answers, regions | |
| Yahoo | 6 endpoints across 35 markets — web search (with ads + related searches), image search, video search, news vertical, autocomplete, markets | Yahoo Docs |
| Yandex | 4 endpoints across 6 markets (tr/com/ru/by/kz/uz) — web search (organic + ads + sitelinks + inline media), image search, reverse-image (CBIR) search, markets | Yandex Docs |
| YouTube | 39 endpoints — search, autocomplete, video detail/related/comments/replies/transcript/captions/streams/live chat/batch, channel detail/videos/shorts/streams/playlists/community/about/subscriber count/search/resolve, playlist detail/items, mixes, trending/shorts, hashtags, home, shorts detail/by sound, community posts/comments, music search, oEmbed, categories/languages/regions/markets | YouTube Guide |
| Immobiliare | 8 endpoints across 4 markets (it, es, gr, lu) — autocomplete, search, listing detail, agency profile/listings, price stats, markets, reference | Immobiliare Guide |
| LoopNet | 5 endpoints across loopnet.com/.ca/.co.uk/.fr/.es — commercial-real-estate search (for-lease/for-sale/auctions), listing detail, broker profile, markets, property types | LoopNet Guide |
| Apartments.com | US rental listings with UNIT-LEVEL pricing — search by location with bed/price filters, plus per-unit rent, beds, baths, sqft and availability for every rentable unit | |
| Baidu | 4 endpoints (baidu.com, China's #1 search engine) — web search with language and date-window filters, news vertical, image search, autocomplete. Results carry the real target URL, not just Baidu's tracking redirect; web search also lists Baidu's own cards (Baike, AI answer, images ...) in cards |
Baidu Docs |
| ChatGPT | Prompt the real chatgpt.com anonymously — structured answer with citations anchored to character offsets, the full retrieved search trail, and AEO/GEO brand-visibility analysis | ChatGPT Guide |
| Gemini | Prompt the real gemini.google.com anonymously — structured answer with cited web sources, the full retrieved search trail, and AEO/GEO brand-visibility analysis | Gemini Docs |
These calls are free and never billed.
import { ScrapeBadger, type AgentTrial } from "scrapebadger";
const client = new ScrapeBadger({ apiKey: "your-api-key" });
// What would a call cost, are its params valid, how long does it take?
const quote = await client.agent.quote("GET", "/v1/google/search", { params: { q: "coffee" } });
console.log(quote.valid, quote.errors, quote.credits.max, quote.usd, quote.latency);
// Poll an async call (see "Async requests and webhooks" below).
const state = await client.requests.get(requestId);
if (state.status === "completed") console.log(state.statusCode, state.creditsUsed, state.body);
// Report a bug or send feedback (pass the failing call's X-Request-ID).
await client.agent.reportBug("Empty results for a valid query", { requestId });
await client.agent.feedback("Need a Google Maps photos endpoint");
// Agent trial keys: account info carries an `agent_trial` block.
const info = await client.account.getAccountInfo();
const trial = info.agent_trial as AgentTrial | undefined;ScrapeBadger does not cache or store responses: every call is fetched fresh and billed, and results.get (the old free re-read) is deprecated because GET /v1/results/{id} was removed on 2026-11-09. To reshape a result, re-run the call with the jq, fields or max_items view parameters. requests.get returns status: "running" while the call is in progress — wait retryAfterSeconds and poll again; never re-submit the call. Once completed it returns the original status, headers and body, or throws the original call's error. The SDK's per-endpoint methods are synchronous; run any of them asynchronously with requests.submit.
Any API call can run asynchronously. Submit it, then wait for it, poll it, or get a signed webhook when it completes. Submitting, polling and waiting are free; the call is billed once, when it completes, at its normal price. Results are kept for about 15 minutes.
import { ScrapeBadger } from "scrapebadger";
const client = new ScrapeBadger({ apiKey: process.env.SCRAPEBADGER_API_KEY! });
// Wait up to 25 s for the answer; a slower call comes back running (HTTP 202).
const run = await client.requests.submit("/v1/perplexity/ask", {
params: { prompt: "best crm for startups", country: "us" },
wait: 25,
idempotencyKey: "crm-us-2026-11-18", // a resubmit with this key is not run or billed again
});
// A call that completed within `wait` is not kept for polling: use it as it is.
const done = run.status === "completed" ? run : await client.requests.wait(run.requestId);
console.log(done.statusCode, done.creditsUsed, done.body);At volume, skip the waiting: give each call a callbackUrl and ScrapeBadger POSTs the result to it when the call completes. Without a wait, a call with a callback answers 202 at once.
const prompts = ["best crm for startups", "best crm for agencies", "best crm for nonprofits"];
for (const [i, prompt] of prompts.entries()) {
const run = await client.requests.submit("/v1/perplexity/ask", {
params: { prompt, country: "us" },
callbackUrl: "https://your-server.example/scrapebadger/webhook",
idempotencyKey: `crm-run-42-${i}`, // safe to resubmit after a crash or a timeout
});
console.log(run.requestId, run.status, run.replayed);
}Every webhook is signed with your account's webhook secret (client.account.webhookSecret(), needs a full-access API key). X-ScrapeBadger-Signature is sha256= plus the hex HMAC-SHA256 of the raw request body, so read the body as bytes. A body parsed and re-serialised will not match.
import express from "express";
import { ScrapeBadger, parseWebhookEvent, verifyWebhookSignature } from "scrapebadger";
import type { WebhookEvent } from "scrapebadger";
const client = new ScrapeBadger({ apiKey: process.env.SCRAPEBADGER_API_KEY! });
const { secret } = await client.account.webhookSecret(); // fetch once and keep it
const seen = new Set<string>(); // use your database in production
const app = express();
// express.raw() keeps the exact bytes that were signed; express.json() would not.
app.post("/scrapebadger/webhook", express.raw({ type: "application/json" }), (req, res) => {
let event: WebhookEvent<{ answer?: string }>;
try {
event = parseWebhookEvent(req.body);
} catch {
return res.sendStatus(400);
}
// Nothing in the event is trusted until this passes. sent_at is part of the
// signed body, so an old delivery replayed later fails the freshness check.
const signature = req.get("X-ScrapeBadger-Signature");
if (!verifyWebhookSignature(secret, req.body, signature, { sentAt: event.sent_at })) {
return res.sendStatus(401);
}
if (!seen.has(event.request_id)) {
seen.add(event.request_id); // deliveries can repeat: deduplicate on request_id
if (event.status === 200) console.log(event.request_id, event.body?.answer);
else console.warn(event.request_id, "failed with", event.status, event.body);
}
res.sendStatus(204);
});
app.listen(3000);event.statusandevent.bodyare the call's own, errors included. A body over 1 MB is left out (body: null,body_omitted: true): fetch it withclient.requests.get(event.request_id)within about 15 minutes.- Answer with any 2xx, quickly. A timeout, a connection error, 408, 429 or 5xx is retried after 10 s, 60 s and 5 min (4 attempts in total).
- Check deliveries with
client.requests.callbackStatus(requestId)(one call) orclient.account.webhookDeliveries({ limit })(the last 24 hours). Rotate the secret withclient.account.rotateWebhookSecret(). submitthrows a refusal before anything runs:invalid_callback_url,async_not_supported,invalid_idempotency_key(400), orConflictErrorwhen anidempotencyKeyis reused for a different call (409). A call that completed withinwaitwith an error status throws that error, like a normal call.- Without an
idempotencyKey, the SDK retries a submit only when the connection failed before anything was sent. A timeout, a network fault, a 429 or a 5xx is thrown, because the call may already be running. With a key, the SDK retries as usual, and a retry answers the existing call (replayed: true). getandwaitthrow the call's own error status as the matching SDK error;waitdoes not retry it, because a stored result does not change.waitthrowsWaitTimeoutError(aTimeoutErrorwithrequestId) when the call is still running attimeoutMs(default ten minutes). The call keeps running: wait or poll again, never resubmit it.- The webhook secret and delivery log need a full-access API key; a key limited to some APIs gets
PermissionDeniedError(403full_access_required).
import {
ScrapeBadger,
AuthenticationError,
RateLimitError,
NotFoundError,
InsufficientCreditsError,
} from "scrapebadger";
const client = new ScrapeBadger({ apiKey: "your-api-key" });
try {
const tweet = await client.twitter.tweets.getById("1234567890");
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Invalid API key");
} else if (error instanceof RateLimitError) {
// Thrown once the SDK's own 429 retries run out
console.error(
`Too many concurrent requests (${error.concurrentRequests}/${error.maxConcurrency}). ` +
`Retry after ${error.retryAfter}s`
);
} else if (error instanceof NotFoundError) {
console.error("Tweet not found");
} else if (error instanceof InsufficientCreditsError) {
console.error("Out of credits");
} else {
throw error;
}
}const client = new ScrapeBadger({
// Required: Your API key (or use SCRAPEBADGER_API_KEY env var)
apiKey: "your-api-key",
// Optional: Custom base URL (default: https://scrapebadger.com)
baseUrl: "https://scrapebadger.com",
// Optional: Request timeout in milliseconds (default: 30000)
timeout: 30000,
// Optional: Maximum retry attempts (default: 10)
maxRetries: 10,
// Optional: Initial retry delay in milliseconds (default: 1000)
retryDelay: 1000,
});The SDK automatically retries requests that fail with server errors (5xx) or with
429 (the account's max concurrency, see below) using exponential backoff (1s, 2s,
4s, 8s, ...), never waiting less than the response's Retry-After. Each retry
prints a colored warning:
⚠ ScrapeBadger: 503 Service Unavailable — retrying in 4s (attempt 3/10)
⚠ ScrapeBadger: 429 Concurrency limit — retrying in 1s (attempt 1/10)
Every ScrapeBadger account has a max concurrency: how many requests it can
have running at the same time, across all of its API keys. There is no
per-minute limit; send as many requests as you like, as long as no more than
max_concurrency are in flight at once. Your plan sets the number, see
pricing.
Check it with the account endpoint (free):
const info = await client.account.getAccountInfo();
console.log(info.max_concurrency); // requests the account may run at once
console.log(info.concurrent_requests); // running right now, not counting this callTo stay under it, cap your own in-flight calls, for example with a small
promise pool (or a library such as p-limit):
const limit = Number((await client.account.getAccountInfo()).max_concurrency) || 1;
// Run fn over items with at most `size` calls in flight.
async function pool<T, R>(items: T[], size: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const results: R[] = new Array(items.length);
let next = 0;
const workers = Array.from({ length: Math.min(size, items.length) }, async () => {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i]);
}
});
await Promise.all(workers);
return results;
}
const users = await pool(["elonmusk", "nasa", "github"], limit, (name) =>
client.twitter.users.getByUsername(name)
);The limit counts every request of the account, whichever key, process or
machine sends it, so split the number between workers that share an account.
The *All iterators fetch one page at a time and hold one slot. An async
request (client.requests.submit) holds its slot until the call finishes;
polling it does not take one.
A request over the limit is refused before it runs, so it is not charged. The
API answers 429 with Retry-After: 1:
{
"error": "concurrency_limit_exceeded",
"detail": "Too many concurrent requests: ...",
"max_concurrency": 5,
"concurrent_requests": 5
}The SDK retries it (see Retry Behavior) and, once retries run out, throws
RateLimitError with maxConcurrency, concurrentRequests and retryAfter
(seconds). Successful responses carry X-Concurrency-Limit (your max
concurrency) and X-Concurrency-Remaining (free slots once this request
started).
ScrapeBadgerError- Base exception classAuthenticationError- Invalid or missing API keyRateLimitError- Too many concurrent requests (429):maxConcurrency,concurrentRequests,retryAfter(seconds)NotFoundError- Resource not foundValidationError- Invalid requestServerError- Server errorTimeoutError- Request timeoutWaitTimeoutError-requests.wait()deadline passed while the call still runs (aTimeoutError)InsufficientCreditsError- Out of creditsAccountRestrictedError- Account restrictedWebSocketStreamError- WebSocket stream failure (auth, limit, or network)
- Node.js 18+ (for native
fetchsupport) - TypeScript 5.0+ (for best type inference)
MIT License - see LICENSE for details.
const page = await client.facebook.searchMarketplace({
query: "bicycle", location: "london", radius: 20, days_since_listed: 2,
sort_by: "creation_time_descend", strict_filters: true, include_details: true,
});No Facebook account is needed. Verified radius is in kilometres using approximate
listing coordinates. Follow end_cursor with the same filters, even after an empty
filtered page. Continuations explore price ranges (eight pages maximum, one-hour
expiry). Coverage and discovery freshness are partial; sort all collected pages by
creation_time_utc and persist IDs for daily deduplication.
