Node.js SDK (2.0.1)
Access the Nstdata Crawl API from your JavaScript and TypeScript applications. Scrape individual pages, submit asynchronous tasks, and crawl websites with configurable depth and page limits.
Retrieve content as Markdown, HTML, links, PDFs, screenshots, or raw data.
GitHub repository (opens in a new tab) · Quick Start (opens in a new tab) · Usage guide (opens in a new tab)
Prerequisites
Before you start, make sure you have:
-
Node.js 22.18 or later within the 22.x release line, or Node.js 24.x.
-
A Nstdata API key (opens in a new tab) with access to the Crawl API.
Installation
Install the SDK in your Node.js project:
npm install @nstdata-ai/crawl@2.0.1The package includes TypeScript definitions and supports ESM and CommonJS imports.
Authentication
Create a .env file in your project directory:
NSTDATA_API_TOKEN=your-api-keyKeep this file out of version control.
Pass the API key to NstDataClient:
import { NstDataClient } from '@nstdata-ai/crawl';
const client = new NstDataClient(process.env.NSTDATA_API_TOKEN);The SDK authenticates requests using the x-api-key header. Keep your API key in your server environment.
Quick Start
Scrape a page and print its Markdown content.
Save the following code as quickstart.mjs:
import {
NstDataClient,
NstDataApiError,
Format,
} from '@nstdata-ai/crawl';
const token = process.env.NSTDATA_API_TOKEN;
if (!token?.trim()) {
throw new Error('Set NSTDATA_API_TOKEN in your environment.');
}
const client = new NstDataClient(token);
try {
const result = await client.submitScrapeTaskSync({
url: 'https://example.com/',
formats: [Format.MARKDOWN],
onlyMainContent: true,
});
if (
result.success === false ||
['failed', 'expired'].includes(result.status)
) {
console.error('Scrape failed:', result.status);
process.exitCode = 1;
} else if (result.status !== 'completed' || !result.data) {
console.error('No completed result is available:', result.status);
process.exitCode = 1;
} else {
const markdown = await result.data.getMarkdown();
if (markdown === undefined) {
console.error('Markdown was not returned.');
process.exitCode = 1;
} else {
if (result.data.truncated === true) {
console.warn('The returned content is truncated.');
}
console.log(markdown);
}
}
} catch (error) {
if (error instanceof NstDataApiError) {
console.error('API request failed:', {
statusCode: error.statusCode,
code: error.code,
});
} else {
console.error(
'Request failed:',
error instanceof Error ? error.name : 'UnknownError',
);
}
process.exitCode = 1;
}Run the script:
node --env-file=.env quickstart.mjsWhen the task completes successfully, the script prints the returned Markdown.
submitScrapeTaskSync() waits for the service response in a single request. It returns a Promise and should be called with await.
Output Formats
| Format | Access | Result | Use |
|---|---|---|---|
Format.MARKDOWN | await data.getMarkdown() | string or undefined | Text and LLM input |
Format.HTML | await data.getHtml() | string or undefined | Parse HTML |
Format.LINKS | data.links | string[] or undefined | Collect URLs |
Format.PDF | await data.getPdf() | Buffer or undefined | Save documents |
Format.SCREENSHOT | await data.getScreenshot() | Buffer or undefined | Capture the page |
Format.RAW_DATA | await data.getRawData() | Buffer or undefined | Read original bytes |
The following snippets reuse the client and imports from the Quick Start. Run each example separately and keep the same result validation and error handling
Use formats to choose the content your application needs. You can request multiple formats in one task.
For example, request Markdown and HTML together:
const result = await client.submitScrapeTaskSync({
url: 'https://example.com/',
formats: [Format.MARKDOWN, Format.HTML],
});After checking that the task completed successfully and result.data is available:
const markdown = await result.data.getMarkdown();
const html = await result.data.getHtml();Content getters use inline content when available and fetch referenced content when needed.
An empty string is a valid result. Use value === undefined to check whether a format is missing.
RAW_DATA returns bytes; it does not perform structured JSON extraction.
Core Workflows
The following snippets reuse the initialized client and Format import from the Quick Start.
Submit an asynchronous scrape
Use asynchronous scraping when you want to submit a task and retrieve its result later.
const task = await client.submitScrapeTask({
url: 'https://example.com/',
formats: [Format.MARKDOWN],
});
if (typeof task.id !== 'string' || !task.id.trim()) {
throw new Error('No task ID was returned.');
}
console.log('Task ID:', task.id);Save the task ID before checking its status.
Retrieve the task in a later request:
const result = await client.getScrapeTaskResult('YOUR_TASK_ID');
console.log('Task status:', result.status);If the task is still processing, query the same task ID again later. Once it completes, validate the result and read its content as shown in the Quick Start.
Submitting a task and checking its result are separate operations. Polling intervals and overall waiting limits are controlled by your application.
Detailed task lifecycle and polling examples: https://github\.com/nstdata\-ai/crawl\-node/blob/main/docs/guide\.md\#asynchronous\-pages (opens in a new tab)
Crawl a website
Start a crawl from one URL and set limits on link discovery:
const crawl = await client.submitCrawlTask({
url: 'https://example.com/',
formats: [Format.MARKDOWN],
maxDepth: 1,
maxPages: 10,
onlyMainContent: false,
});
if (typeof crawl.id !== 'string' || !crawl.id.trim()) {
throw new Error('No crawl ID was returned.');
}
console.log('Crawl ID:', crawl.id);maxPages is an upper limit. The actual number of pages depends on the pages discovered and the crawl configuration.
Keeping onlyMainContent: false can help retain navigation links used for discovery.
Check progress using the saved crawl ID:
const status = await client.getCrawlStatus('YOUR_CRAWL_ID');
console.log(status);Wait until the crawl status is completed before retrieving results.
If the status is processing or scraping, wait a few seconds and call getCrawlStatus again using the same crawl ID. If the status is failed or expired, handle the task as failed.
Once the crawl is completed, retrieve a page of results:
const batch = await client.listCrawlPages('YOUR_CRAWL_ID', {
limit: 20,
});
console.log('Pages in this response:', batch.data?.length ?? 0);
console.log('Next cursor:', batch.nextCursor);The pagination limit controls the number of records returned in one request. It is separate from the crawl’s maxPages setting.
Complete crawl and pagination examples: https://github\.com/nstdata\-ai/crawl\-node/blob/main/docs/guide\.md\#site\-crawling (opens in a new tab)
Render JavaScript and run page actions
Use jsRender when a page needs JavaScript execution or interactions before content collection.
import { ActionBuilder } from '@nstdata-ai/crawl';
const result = await client.submitScrapeTaskSync({
url: 'https://example.com/',
formats: [Format.MARKDOWN],
jsRender: {
waitForSelector: 'h1',
actions: [
ActionBuilder.scrollY(400),
ActionBuilder.wait(1000),
],
},
});Choose selectors and actions that match the target page. Available action builders include clicking, filling inputs, waiting for selectors, scrolling, and executing JavaScript.
Validate the returned task result before reading its content.
Rendering options and action reference: https://github\.com/nstdata\-ai/crawl\-node/blob/main/docs/guide\.md\#javascript\-rendering (opens in a new tab)
Request Configuration
| Field | Purpose |
|---|---|
url、formats | Target page and requested outputs |
onlyMainContent | Extract the main content |
targetSelector、removeSelectors | Select a subtree or remove matching elements |
includeTags、excludeTags | Include or exclude tags |
headers、cookies | Supply request headers and cookies |
proxy.country | Select the proxy country |
mobile | Use mobile rendering |
timeout | Service timeout in milliseconds (1,000–60,000) |
jsRender | Configure rendering, waits and page actions |
maxPages、maxDepth | Limit page count and discovery depth |
includeUrls、excludeUrls、ignoreQuery | Control crawl URL matching |
Customize scraping behavior through the request object.
Website crawls also support options including maxPages, maxDepth, includeUrls, excludeUrls, and ignoreQuery.
Refer to the API documentation for accepted values, constraints, defaults, and URL matching rules.
Read Request fields and constraints (opens in a new tab)
Client and request controls
Configure the client’s default HTTP timeout:
const client = new NstDataClient(token, {
timeoutMs: 120_000,
});Override controls for an individual request:
const result = await client.getScrapeTaskResult(
'YOUR_TASK_ID',
{
timeoutMs: 30_000,
signal: AbortSignal.timeout(10_000),
maxResponseBytes: 1_048_576,
},
);A local timeout or cancellation stops local waiting. It does not cancel the remote task.
Client options and method signatures: https://github\.com/nstdata\-ai/crawl\-node/blob/main/docs/guide\.md\#reference (opens in a new tab)
Results and Error Handling
Check both the task status and the returned data before using a result.
A completed crawl can still contain unsuccessful pages. Validate each page individually.
The SDK exposes API errors through NstDataApiError. Use fields such as statusCode and code for diagnostics, as shown in the Quick Start.
The SDK does not automatically retry requests. If a submission times out, the server may already have accepted it; inspect task history before creating another task.
Request controls and error handling: https://github\.com/nstdata\-ai/crawl\-node/blob/main/docs/guide\.md\#request\-controls\-and\-errors (opens in a new tab)
Troubleshooting
| Symptom | Resolution |
|---|---|
| Missing API key | Load the key into the running process. Load .env explicitly if used. |
| Authentication or quota error | Check Crawl access, key validity, API status and available credits. |
| Task still running | Resume polling with the saved asynchronous task ID. |
| Missing Markdown or HTML | Request that format, verify completion, success and data, then use the content getter. |
| Missing dynamic content | Configure JavaScript rendering, waits and selectors for the target page. |
| Local timeout | Check client and service timeout units. Save the task ID before retrying. |
| Truncated output | Inspect the truncation flag on the returned data. |