How to Use Talordata SERP API with JavaScript

Learn how to use Talordata SERP API with JavaScript. Send search requests, parse organic results, handle errors, batch keywords, export CSV data, and build SEO or AI search workflows.

How to Use Talordata SERP API with JavaScript
Cecilia Hill
Last updated on
6 min read

JavaScript is a practical choice for SERP API workflows.

You can use it in a backend service, an internal SEO tool, a Next.js app, an AI agent, a data collection script, or a scheduled job that checks search results every day.

The goal is simple:

send query
→ get structured search results
→ parse useful fields
→ store or pass the data into your product

Talordata SERP API helps developers collect structured search-result data and use it in SEO dashboards, rank tracking systems, competitor monitoring tools, AI agents, and market research workflows.

This tutorial shows how to call Talordata SERP API with JavaScript, parse search results, handle errors, run batch keyword checks, export CSV data, and prepare compact search context for AI workflows.

Quick answer

To use Talordata SERP API with JavaScript, create a Node.js script, read your API key from environment variables, send a POST request to your SERP API endpoint, pass parameters such as engine, q, location, gl, hl, device, and num, then parse the returned JSON.

A basic workflow looks like this:

JavaScript app
→ SERP API request
→ JSON response
→ parse organic results
→ store results or send them to an AI / SEO workflow

When should you use a SERP API in JavaScript?

A SERP API is useful when your application needs search engine results as data.

Use case

What JavaScript does

SEO rank tracking

Collect keyword positions and target URLs

Competitor monitoring

Check which domains appear for important queries

AI agents

Provide fresh search context before answering

RAG workflows

Discover current web sources

Content briefs

Extract ranking pages, snippets, and search intent

Local SEO

Compare rankings by city, language, and device

E-commerce monitoring

Track Shopping, pricing, and seller visibility

News and trend monitoring

Collect fresh search signals over time

In most cases, JavaScript is not doing anything mysterious. It sends a request, receives structured data, cleans the fields, and passes the result to the next part of the workflow.

Small pipe, useful water. 🪄

Step 1: Create a Node.js project

Create a new folder:

mkdir talordata-serp-js
cd talordata-serp-js
npm init -y

Use Node.js 18 or later so you can use the built-in fetch API.

Check your Node version:

node -v

If you are using an older Node version, install node-fetch or upgrade Node.

Step 2: Set environment variables

Do not hardcode your API key in the script.

On macOS or Linux:

export TALORDATA_API_KEY="your_api_key_here"
export TALORDATA_SERP_ENDPOINT="your_serp_api_endpoint_here"

On Windows PowerShell:

$env:TALORDATA_API_KEY="your_api_key_here"
$env:TALORDATA_SERP_ENDPOINT="your_serp_api_endpoint_here"

Keep the endpoint configurable. Use the endpoint shown in your Talordata dashboard or API documentation.

A leaked API key is not a tiny bug. It is a tiny dragon with a credit card.

Step 3: Send your first search request

Create a file named search.js.

const API_KEY = process.env.TALORDATA_API_KEY;
const SERP_ENDPOINT = process.env.TALORDATA_SERP_ENDPOINT;

if (!API_KEY) {
  throw new Error("Missing TALORDATA_API_KEY environment variable.");
}

if (!SERP_ENDPOINT) {
  throw new Error("Missing TALORDATA_SERP_ENDPOINT environment variable.");
}

async function searchGoogle(query) {
  const response = await fetch(SERP_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      engine: "google",
      q: query,
      location: "United States",
      gl: "us",
      hl: "en",
      device: "desktop",
      num: 10,
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`SERP API request failed: ${response.status} ${errorText}`);
  }

  return response.json();
}

async function main() {
  const data = await searchGoogle("best project management software");
  console.log(JSON.stringify(data, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});

Run it:

node search.js

If everything is configured correctly, you should receive a JSON response containing search result data.

Step 4: Understand the common request parameters

Most JavaScript workflows need only a few parameters at first.

Parameter

Meaning

engine

Search engine or search type

q

Search query

location

Target location

gl

Country or market

hl

Search language

device

Desktop or mobile

num

Number of results

start

Pagination offset

json or output control

Used in some request formats to control structured output

For SEO and AI workflows, q, location, gl, hl, and device are especially important. Search results can change by country, city, language, and device, so a query without context can be misleading. View the complete API documentation>>

Step 5: Parse organic results

Raw JSON is useful, but most applications need a smaller structure.

Create a helper function:

function cleanText(value) {
  if (!value) return "";
  return String(value).replace(/\s+/g, " ").trim();
}

function getOrganicResults(data) {
  return data.organic_results || data.organic || data.results || [];
}

function normalizeOrganicResults(data) {
  const organicResults = getOrganicResults(data);

  return organicResults.map((item, index) => ({
    position: item.position || item.rank || index + 1,
    title: cleanText(item.title),
    url: item.link || item.url || "",
    snippet: cleanText(item.snippet || item.description),
    displayedLink: cleanText(item.displayed_link || item.displayedUrl),
  }));
}

Use it in your script:

async function main() {
  const data = await searchGoogle("best project management software");
  const results = normalizeOrganicResults(data);

  console.table(results);
}

Now the output is easier to read and easier to store.

Step 6: Track whether a target domain ranks

For SEO rank tracking, you often want to know whether a specific domain appears in the results.

function extractHostname(url) {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return "";
  }
}

function findTargetDomain(results, targetDomain) {
  const target = targetDomain.replace(/^www\./, "").toLowerCase();

  for (const result of results) {
    const hostname = extractHostname(result.url).toLowerCase();

    if (hostname === target || hostname.endsWith(`.${target}`)) {
      return {
        found: true,
        position: result.position,
        matchedUrl: result.url,
        title: result.title,
        snippet: result.snippet,
      };
    }
  }

  return {
    found: false,
    position: null,
    matchedUrl: "",
    title: "",
    snippet: "",
  };
}

Example:

async function main() {
  const keyword = "best project management software";
  const targetDomain = "example.com";

  const data = await searchGoogle(keyword);
  const results = normalizeOrganicResults(data);
  const ranking = findTargetDomain(results, targetDomain);

  console.log({
    keyword,
    targetDomain,
    ...ranking,
  });
}

This gives you a simple rank tracking building block.

Step 7: Run batch keyword searches

Most real workflows need more than one query.

const KEYWORDS = [
  "best project management software",
  "crm software for small business",
  "email marketing tools",
];

const SEARCH_CONTEXT = {
  location: "United States",
  gl: "us",
  hl: "en",
  device: "desktop",
  num: 10,
};

async function searchWithContext(query, context) {
  const response = await fetch(SERP_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      engine: "google",
      q: query,
      ...context,
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Request failed for "${query}": ${response.status} ${errorText}`);
  }

  return response.json();
}

async function runBatchSearch() {
  const rows = [];

  for (const keyword of KEYWORDS) {
    const data = await searchWithContext(keyword, SEARCH_CONTEXT);
    const results = normalizeOrganicResults(data);

    for (const result of results) {
      rows.push({
        keyword,
        location: SEARCH_CONTEXT.location,
        gl: SEARCH_CONTEXT.gl,
        hl: SEARCH_CONTEXT.hl,
        device: SEARCH_CONTEXT.device,
        ...result,
        collectedAt: new Date().toISOString(),
      });
    }
  }

  console.table(rows);
}

runBatchSearch().catch((error) => {
  console.error(error);
  process.exit(1);
});

This is enough for a small internal SEO script or AI search prototype.

For larger workloads, add rate limiting, retries, queues, and persistent storage.

Step 8: Export results to CSV

JavaScript can generate CSV without extra packages.

import fs from "node:fs";

function escapeCsvValue(value) {
  const text = value == null ? "" : String(value);
  return `"${text.replace(/"/g, '""')}"`;
}

function writeCsv(rows, filename) {
  if (!rows.length) {
    fs.writeFileSync(filename, "", "utf8");
    return;
  }

  const headers = Object.keys(rows[0]);

  const lines = [
    headers.join(","),
    ...rows.map((row) =>
      headers.map((header) => escapeCsvValue(row[header])).join(",")
    ),
  ];

  fs.writeFileSync(filename, lines.join("\n"), "utf8");
}

If your project uses ES modules, add this to package.json:

{
  "type": "module"
}

Then export your batch results:

async function runBatchSearchToCsv() {
  const rows = [];

  for (const keyword of KEYWORDS) {
    const data = await searchWithContext(keyword, SEARCH_CONTEXT);
    const results = normalizeOrganicResults(data);

    for (const result of results) {
      rows.push({
        keyword,
        location: SEARCH_CONTEXT.location,
        gl: SEARCH_CONTEXT.gl,
        hl: SEARCH_CONTEXT.hl,
        device: SEARCH_CONTEXT.device,
        position: result.position,
        title: result.title,
        url: result.url,
        snippet: result.snippet,
        displayedLink: result.displayedLink,
        collectedAt: new Date().toISOString(),
      });
    }
  }

  writeCsv(rows, "serp_results.csv");
  console.log(`Exported ${rows.length} rows to serp_results.csv`);
}

runBatchSearchToCsv().catch((error) => {
  console.error(error);
  process.exit(1);
});

Now your JavaScript script can collect search results and produce a spreadsheet-friendly file.

Step 9: Handle errors and retries

Network calls fail. APIs return errors. Queries may return empty results.

Do not let one failed keyword kill the whole batch.

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function withRetry(fn, retries = 3, delayMs = 1000) {
  let lastError;

  for (let attempt = 1; attempt <= retries; attempt += 1) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      console.warn(`Attempt ${attempt} failed: ${error.message}`);

      if (attempt < retries) {
        await sleep(delayMs * attempt);
      }
    }
  }

  throw lastError;
}

Use it like this:

const data = await withRetry(() => searchWithContext(keyword, SEARCH_CONTEXT));

For production systems, also log:

  • request payload

  • response status

  • keyword

  • location

  • device

  • timestamp

  • retry count

This makes debugging less like reading tea leaves in a thunderstorm.

Step 10: Use results in an AI workflow

If you are building an AI assistant, do not send the entire SERP response into the model.

Send a compact context.

function buildSearchContext(results, limit = 5) {
  return results.slice(0, limit).map((result) => ({
    title: result.title,
    url: result.url,
    snippet: result.snippet,
    position: result.position,
  }));
}

Example:

async function getSearchContextForAi(query) {
  const data = await searchGoogle(query);
  const results = normalizeOrganicResults(data);

  return {
    query,
    results: buildSearchContext(results, 5),
  };
}

This is useful for:

  • AI research assistants

  • content brief generators

  • RAG source discovery

  • competitor summaries

  • real-time market monitoring

  • fact-checking workflows

Structured search data keeps the model focused. Raw pages often turn the context window into a messy attic.

Best practices

Keep API keys in environment variables. Never commit them to Git.

Start with one query before running batch jobs. Debug the request first, then scale.

Always store query context. Save q, engine, location, gl, hl, device, and collectedAt.

Normalize the response before storing it. Your database should not depend on every raw API field staying exactly the same.

Separate organic results, ads, maps, shopping, news, and videos when your workflow needs different result types.

Use retries, but do not retry forever. A retry loop without limits is just a tiny robot panic attack.

For AI workflows, pass only the fields the model needs: title, URL, snippet, position, and source.

For SEO workflows, store historical snapshots. One SERP result is a photograph. A ranking database is the time-lapse.

FAQ

Can I use Talordata SERP API with JavaScript?

Yes. You can call Talordata SERP API from JavaScript using Node.js fetch, axios, or any HTTP client. Most workflows send a POST request with search parameters and receive structured JSON.

Do I need Node.js?

For backend scripts, scheduled jobs, and server-side apps, Node.js is the most common choice. Avoid calling SERP APIs directly from frontend browser code because that would expose your API key.

Which search parameters should I use first?

Start with engine, q, location, gl, hl, device, and num. These cover the search engine, query, market, language, device, and result count.

Can I use this for SEO rank tracking?

Yes. Parse organic results, match your target domain, store the ranking position, and repeat the process over time for the same keyword and location set.

Can I use this for AI agents?

Yes. Use the SERP API to collect fresh search results, then pass compact fields such as title, URL, snippet, and position into the model as context.

Should I store raw responses?

During development, yes. Raw responses help debug parser issues. In production, store normalized fields for dashboards and keep raw responses only when your compliance, debugging, or auditing needs require them.

Should I use JSON or HTML output?

Use JSON for most JavaScript workflows, especially SEO dashboards, databases, and AI agents. Use HTML only when you need raw SERP inspection or custom parsing.

Scale Your Data
Operations Today.

Join the world's most robust proxy network.

Start Free Trial