Skip to content
Docs
SDKs
Node.js

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:

Installation

Install the SDK in your Node.js project:

npm install @nstdata-ai/crawl@2.0.1

The package includes TypeScript definitions and supports ESM and CommonJS imports.

Authentication

Create a .env file in your project directory:

NSTDATA_API_TOKEN=your-api-key

Keep 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.mjs

When 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

FormatAccessResultUse
Format.MARKDOWNawait data.getMarkdown()string or undefinedText and LLM input
Format.HTMLawait data.getHtml()string or undefinedParse HTML
Format.LINKSdata.linksstring[] or undefinedCollect URLs
Format.PDFawait data.getPdf()Buffer or undefinedSave documents
Format.SCREENSHOTawait data.getScreenshot()Buffer or undefinedCapture the page
Format.RAW_DATAawait data.getRawData()Buffer or undefinedRead 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

FieldPurpose
url、formatsTarget page and requested outputs
onlyMainContentExtract the main content
targetSelector、removeSelectorsSelect a subtree or remove matching elements
includeTags、excludeTagsInclude or exclude tags
headers、cookiesSupply request headers and cookies
proxy.countrySelect the proxy country
mobileUse mobile rendering
timeoutService timeout in milliseconds (1,000–60,000)
jsRenderConfigure rendering, waits and page actions
maxPages、maxDepthLimit page count and discovery depth
includeUrls、excludeUrls、ignoreQueryControl 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

SymptomResolution
Missing API keyLoad the key into the running process. Load .env explicitly if used.
Authentication or quota errorCheck Crawl access, key validity, API status and available credits.
Task still runningResume polling with the saved asynchronous task ID.
Missing Markdown or HTMLRequest that format, verify completion, success and data, then use the content getter.
Missing dynamic contentConfigure JavaScript rendering, waits and selectors for the target page.
Local timeoutCheck client and service timeout units. Save the task ID before retrying.
Truncated outputInspect the truncation flag on the returned data.