JavaScript SDK Specification

    JavaScript SDK Specification

    Examples on this page match desearch-js@1.5.1. extract() is the extract call. webCrawl() remains a deprecated alias on this version. New code should call extract().

    First Search call: Search API. Page fetch: Extract API. Keys: Auth and API keys.

    Install

    Requires Node.js 20.18.1 or later. Node 18 is not supported. npm still installs the package on Node 18 with an EBADENGINE warning, but that setup is not tested.

    Pin the version used in these examples:

    BASH
    npm install desearch-js@1.5.1

    Use 1.5.1 or later. On 1.5.0, importing the package could crash with TypeError: webidl.util.markAsUncloneable is not a function when the package manager installed undici 8 at the top level of the project. 1.5.1 limits its undici dependency to versions 6 and 7 and loads correctly even when undici 8 is present.

    Construct the client

    Desearch is both the default export and a named export. Pass the raw API key. Do not expose production keys in browser bundles.

    ES modules:

    JAVASCRIPT
    import Desearch from "desearch-js";
    // or: import { Desearch } from "desearch-js";
    
    const desearch = new Desearch(process.env.DESEARCH_API_KEY);

    CommonJS:

    JAVASCRIPT
    const { Desearch } = require("desearch-js");
    
    async function main() {
      const desearch = new Desearch(process.env.DESEARCH_API_KEY);
      const result = await desearch.search({
        query: "latest AI search API notes",
        count: 10,
      });
      console.log(result);
    }
    
    main();

    Do not pass streaming into aiSearch. The method always sends a non-stream request. For "streaming": true, call REST. See Streaming AI Search.

    search calls POST /search. It returns ranked web pages, each with the passage that best matches the query. Set summary: true to also get a short answer with numbered citations.

    JAVASCRIPT
    const result = await desearch.search({
      query: "Who won the 2024 Nobel Prize in Physics?",
      count: 10,
      summary: true,
    });
    
    console.log(result.summary?.text);
    for (const citation of result.summary?.citations ?? []) {
      console.log(citation.index, citation.url);
    }

    summary is null when the summary could not be written; the results are still returned. See the Search API guide for every field.

    Extract

    JAVASCRIPT
    const content = await desearch.extract({
      url: "https://en.wikipedia.org/wiki/Artificial_intelligence",
      format: "text",
    });

    Billing metadata

    Read request cost from response headers. JSON object bodies may also include cost_usd, usage_count, service, and currency.

    HeaderMeaning
    X-Desearch-Cost-UsdRequest cost in USD
    X-Desearch-Usage-CountBillable usage units
    X-Desearch-ServicePricing service key
    X-Desearch-CurrencyCurrency code

    Arrays, text responses, and streaming responses keep their body shape. Use headers for those. This page does not list dollar rates.

    Errors

    • Missing or invalid key: 401.
    • Validation failure: 4xx with the API message.
    • 429 or 5xx: retry with backoff.

    Do not invent error JSON schemas beyond the API Reference.

    Parity with Python

    CapabilityPython 1.2.1JavaScript 1.5.1
    Search (POST /search), with summary (JavaScript 1.15.0)search(...)search({...})
    AI Search (X posts and web)ai_search(...)aiSearch({...})
    Extract page contentREST /web/extract or web_crawlextract({...})
    Streaming helpersNot on this package. Use REST (streaming guide)Same
    Billing fields on a JSON objectRead body and headersSame
    Billing on a streamHeaders onlyHeaders only
    People Search (Python 1.4.0, JavaScript 1.6.0)x_profile_search(...), youtube_creator_search(...), linkedin_profile_search(...), tiktok_creator_search(...)xProfileSearch({...}), youtubeCreatorSearch({...}), linkedinProfileSearch({...}), tiktokCreatorSearch({...})
    Wait for a People Search taskwait_for_people_task(task_id)waitForPeopleTask(task)
    Read every People Search resultiter_people_results(task_id)iterPeopleResultPages({ task_id })
    People Search metadata labels (Python 1.5.0, JavaScript 1.7.0)metadata={...} on the search methods and list_people_tasksmetadata: {...} in the search request and in listPeopleTasks
    People Search result fields (Python 1.6.1, JavaScript 1.8.1)task.completion_reason, score.unverified_criteria, person.enrichmenttask.completion_reason, unverifiedCriteria(person.score), person.attributes?.enrichment
    Company Search and Company Enrich (Python 1.10.0, JavaScript 1.11.0)company_search(...), company_enrich(...)companySearch({...}), companyEnrich({...})
    Wait for a company task, read every companywait_for_company_task(task_id), iter_company_results(task_id)waitForCompanyTask(task), iterCompanyResults({ task_id })
    Monitors (JavaScript 1.14.0). See the Monitors guideNot on this package. Use REST (Monitors guide)createMonitor({...}), estimateMonitor({...}), listMonitors(), getMonitor({...}), updateMonitor({...}, {...}), deleteMonitor({...}), triggerMonitor({...}), listMonitorRuns({...}), getMonitorRun({...}), listMonitorItems({...}), iterMonitorItems({...}), testMonitorWebhook({...}), rotateMonitorWebhookSecret({...}); webhook check: verifyWebhookSignature(secret, header, body) (named export)

    Python extract() is not on PyPI desearch-py 1.2.1. See the Python SDK.

    Other methods already on this package

    SERP web search (GET /web):

    JAVASCRIPT
    const result = await desearch.webSearch({
      query: "latest AI search news",
      num: 10,
      start: 0,
    });
    
    console.log(result);

    X search:

    JAVASCRIPT
    const result = await desearch.xSearch({
      query: "Bittensor",
      sort: "Top",
      count: 20,
    });
    
    console.log(result);

    People Search (1.6.0 and later)

    People Search methods ship in desearch-js 1.6.0. The examples above match 1.5.1.

    BASH
    npm install desearch-js@^1.6.0

    A search runs in the background. Start it, wait for it, then read or export the people it found:

    JAVASCRIPT
    import { randomUUID } from "node:crypto";
    import Desearch from "desearch-js";
    
    const desearch = new Desearch(process.env.DESEARCH_API_KEY);
    
    // The only billed call. It returns a queued task at once.
    const task = await desearch.xProfileSearch(
      { query: "Indie hackers building in public who share their MRR", count: 10 },
      { idempotencyKey: randomUUID() },
    );
    
    // Polls until the task ends. Free.
    await desearch.waitForPeopleTask(task, { intervalMs: 5000, timeoutMs: 10 * 60 * 1000 });
    
    for await (const page of desearch.iterPeopleResultPages({ task_id: task.task_id, limit: 100 })) {
      for (const person of page.results) {
        console.log(person.handle, person.score?.value);
      }
    }
    
    const csv = await desearch.exportPeopleResults({ task_id: task.task_id, format: "csv" });
    console.log(csv.length);
    MethodRoute
    xProfileSearch, youtubeCreatorSearch, linkedinProfileSearch, tiktokCreatorSearchPOST /desearch/people/search/{x,youtube,linkedin,tiktok} (billed)
    listPeopleTasksGET /desearch/people/tasks
    getPeopleTaskGET /desearch/people/tasks/{task_id}
    getPeopleResultsGET /desearch/people/tasks/{task_id}/results
    pausePeopleTask, resumePeopleTask, cancelPeopleTaskPOST /desearch/people/tasks/{task_id}/pause, /resume, /cancel
    exportPeopleResultsGET /desearch/people/tasks/{task_id}/export
    listPeopleProfilesGET /desearch/people/profiles
    exportPeopleProfilesGET /desearch/people/profiles/export
    waitForPeopleTaskPolls getPeopleTask until the task ends
    iterPeopleResultPagesFollows next_cursor on getPeopleResults

    Each search request takes query, count, min_score, exclude, and that platform's filters, plus metadata from 1.7.0 (below). idempotencyKey in the second argument is sent as the Idempotency-Key header. Pause, resume, and cancel throw PeopleTaskConflictError on HTTP 409. waitForPeopleTask throws when timeoutMs passes; the search keeps running. Flow, filters, and billing: People Search.

    Read why a search ended and what each result confirms (1.8.0 and later)

    desearch-js 1.8.0 adds types for the result fields and the helper unverifiedCriteria. 1.8.1 adds is_disqualifier on each check.

    BASH
    npm install desearch-js@^1.8.1
    JAVASCRIPT
    import Desearch, { unverifiedCriteria } from "desearch-js";
    
    const desearch = new Desearch(process.env.DESEARCH_API_KEY);
    
    const done = await desearch.waitForPeopleTask({ task_id: taskId });
    console.log(done.completion_reason, done.coverage_limited); // e.g. count_reached false
    for (const warning of done.warnings ?? []) {
      console.log(warning.code, warning.platform, warning.failed, warning.attempted, warning.by_reason);
    }
    
    for await (const page of desearch.iterPeopleResultPages({ task_id: taskId })) {
      for (const person of page.results) {
        const unverified = unverifiedCriteria(person.score).map((check) => check.criterion);
        console.log(person.handle, person.score?.fully_verified, unverified);
        if (person.attributes?.enrichment === "failed") {
          console.log("profile not read:", person.attributes.enrichment_error);
        }
      }
    }
    • completion_reason is null while the search runs. coverage_limited is true when a budget stopped it before count.
    • score.criteria_checks is a PeopleCriterionCheck[] (criterion, verdict, quote, source_url, reason, is_disqualifier). unverifiedCriteria(score) returns the checks that are not met, plus the disqualifiers that are met. A check without is_disqualifier, scored before the field existed, counts as a disqualifier when its criterion names one, such as disqualify or exclude.
    • person.attributes is a PersonAttributes with enrichment (ok or failed) and enrichment_error.

    What each field means: the Reading results section of People Search.

    Label searches with metadata (1.7.0 and later)

    desearch-js 1.7.0 adds metadata to the four search methods and a metadata option to listPeopleTasks. Use it to tag each search with your own labels, such as the campaign, workspace, or customer it belongs to, and to list those searches later. The search itself never uses the labels.

    BASH
    npm install desearch-js@^1.7.0
    JAVASCRIPT
    import { randomUUID } from "node:crypto";
    import Desearch from "desearch-js";
    
    const desearch = new Desearch(process.env.DESEARCH_API_KEY);
    
    const task = await desearch.xProfileSearch(
      {
        query: "Indie hackers building in public who share their MRR",
        count: 10,
        metadata: { campaign: "q4-outbound", workspace_id: "ws_42" },
      },
      { idempotencyKey: randomUUID() },
    );
    console.log(task.metadata); // { campaign: 'q4-outbound', workspace_id: 'ws_42' }
    
    // Later: every search of that campaign, newest first.
    const { tasks } = await desearch.listPeopleTasks({
      metadata: { campaign: "q4-outbound" },
    });
    for (const t of tasks) {
      console.log(t.task_id, t.status, t.metadata.workspace_id);
    }
    • task.metadata is {} for a search without labels.
    • A search takes up to 10 keys. Keys are 1 to 40 characters of a-z, 0-9, _, ., or -, and values are strings of up to 200 characters. The SDK does not check them; the API answers 422 otherwise.
    • listPeopleTasks sends each pair as a metadata.<key>=<value> query parameter, and a task must match all of them exactly. Pass up to 3 pairs (the API answers 400 otherwise), and pass the same metadata with each cursor when you page.
    • This metadata is the task's labels. It is not the cost metadata that { includeMetadata: true } returns.

    Company Search (1.11.0 and later)

    Company Search and Company Enrich methods ship in desearch-js 1.11.0.

    BASH
    npm install desearch-js@^1.11.0

    A task runs in the background. Start it, wait for it, then read or export the companies it delivered:

    JAVASCRIPT
    import { randomUUID } from "node:crypto";
    import Desearch, { unverifiedCriteria } from "desearch-js";
    
    const desearch = new Desearch(process.env.DESEARCH_API_KEY);
    
    // The only billed call. It returns a queued task at once.
    const task = await desearch.companySearch(
      {
        query: "Series A fintech startups in Berlin building payment infrastructure",
        count: 25,
        min_score: 60,
        filters: { countries: ["DE"], require: ["email"] },
        metadata: { campaign: "q4" },
      },
      { idempotencyKey: randomUUID() },
    );
    console.log(task.task_id, task.status, task.reserved_cost_usd);
    
    // Polls until the task ends. Free.
    const done = await desearch.waitForCompanyTask(task, {
      intervalMs: 5000,
      timeoutMs: 30 * 60 * 1000,
      onProgress: (t) => console.log(t.status, t.stage, `${t.result_count}/${t.count}`),
    });
    console.log(done.completion_reason, done.final_cost_usd);
    
    for await (const company of desearch.iterCompanyResults({ task_id: task.task_id })) {
      console.log(company.domain, company.score?.value, company.primary_email?.value);
      for (const person of company.people) {
        for (const email of person.emails) {
          console.log("  ", person.name, person.roles, email.value, email.source, email.verification?.status);
        }
      }
      if (company.score) {
        console.log("  unverified:", unverifiedCriteria(company.score).map((check) => check.criterion));
      }
    }
    
    const csv = await desearch.exportCompanyResults({ task_id: task.task_id, format: "csv" });
    console.log(csv.length);

    Company Enrich takes domains or URLs instead of a description:

    JAVASCRIPT
    const enrich = await desearch.companyEnrich(
      { domains: ["acme.com", "https://www.beta.io/about"], roles: ["ceo", "cto"] },
      { idempotencyKey: randomUUID() },
    );
    console.log(enrich.query, enrich.count); // acme.com, beta.io 2
    await desearch.waitForCompanyTask(enrich);
    for await (const company of desearch.iterCompanyResults({ task_id: enrich.task_id })) {
      console.log(company.domain, company.score); // score is null for Company Enrich
    }
    MethodRoute
    companySearch, companyEnrichPOST /desearch/companies/search, POST /desearch/companies/enrich (billed)
    listCompanyTasksGET /desearch/companies/tasks
    getCompanyTaskGET /desearch/companies/tasks/{task_id}
    getCompanyResultsGET /desearch/companies/tasks/{task_id}/results
    pauseCompanyTask, resumeCompanyTask, cancelCompanyTaskPOST /desearch/companies/tasks/{task_id}/pause, /resume, /cancel
    exportCompanyResultsGET /desearch/companies/tasks/{task_id}/export
    waitForCompanyTaskPolls getCompanyTask until the task ends
    iterCompanyResultsFollows next_cursor on getCompanyResults and yields each company
    • The task methods take a params object, like the People Search methods: getCompanyTask({ task_id }), getCompanyResults({ task_id, cursor, limit }), exportCompanyResults({ task_id, format }), and listCompanyTasks({ type, status, limit, cursor, metadata }), where type is search or enrich and metadata is a filter of up to 3 pairs.
    • idempotencyKey in the second argument of companySearch and companyEnrich is sent as the Idempotency-Key header.
    • A company is published before every stage has run and is filled in later. iterCompanyResults yields each company as it is when its page is read, so read after waitForCompanyTask returns to get the final version. On a running task, call getCompanyResults without cursor to read every company in its latest version.
    • unverifiedCriteria(score) works on a CompanyScore as on a People Search score. score is null for Company Enrich.
    • Pause, resume, and cancel throw CompanyTaskConflictError on HTTP 409, with detail and the current task. waitForCompanyTask throws when timeoutMs passes; the task keeps running.

    Flow, result fields, and billing: Company Search.

    Next