Integration

Google Search API with Node.js

Modern Node.js includes fetch, so a search request does not need another HTTP package. The example below is ready for trusted server code.

Copy the complete Node.js example

Set GSEARCH_API_KEY in the server environment. The code sends JSON, applies a 10 second deadline, checks the status, and returns the ordered organic array.

Node.js ยท javascript

async function googleSearch(query, options = {}) {
  const apiKey = process.env.GSEARCH_API_KEY;
  if (!apiKey) throw new Error("GSEARCH_API_KEY is not set");

  const response = await fetch("https://gsearch.dev/api/v1/search", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": apiKey
    },
    body: JSON.stringify({
      q: query,
      gl: options.gl ?? "us",
      hl: options.hl ?? "en",
      page: options.page ?? 1
    }),
    signal: AbortSignal.timeout(10_000)
  });

  const body = await response.json().catch(() => null);
  if (!response.ok) {
    throw new Error([
      response.status,
      body?.error?.code ?? "SEARCH_FAILED",
      body?.error?.message ?? "Search request failed",
      body?.error?.requestId ?? "no request ID"
    ].join(" "));
  }
  if (!body || !Array.isArray(body.organic)) {
    throw new Error("Search API returned an invalid JSON response");
  }

  return body.organic;
}

const results = await googleSearch("Ada Lovelace");
console.log(results);

Check status and JSON shape

Read the response body once, then check response.ok before using organic. Error bodies contain an error object with code, message, and requestId instead of search results.

If query options come from an end user, validate them before the API call. Page must be an integer from 1 through 10, and country and language values must be supported codes.

Use timeouts and limited retries

AbortSignal.timeout prevents a slow request from waiting forever. Catch timeout errors separately so your application can return a clear temporary failure.

Retry only temporary 429, 502, 503, and 504 responses. Use increasing delays, stop after a small number of attempts, and respect the plan rate limit.

Keep the key in the server runtime

Store the key as a secret in your hosting platform and read it from process.env. Do not send the key to frontend JavaScript or expose it through a public API response.

For client applications, create your own server endpoint that accepts only the query fields you want to support.

Next steps