Skip to content
EN
Get API key
Browse documentation

Guides

Add search to an application

Build a working search form, keep the API key on your backend, and reuse the same search function in an agent tool.

On this page

What you will build

A local search form with ranked links, snippets and credit usage. Requires Node.js 22+, a key with google_search permission and available credits. No npm packages are needed. The optional agent section reuses the same backend function.

Save in flashdata-search-demoPurpose
search.mjsCalls FlashData from the backend; shared by the form and agent tool.
server.mjsServes the local page and GET /search endpoint.
index.htmlDisplays sources, empty results and errors.
Bash or PowerShell · create the project
node --version
mkdir flashdata-search-demo
cd flashdata-search-demo

Set your API key

Reuse FLASHDATA_API_KEY if already set. Otherwise use the hidden prompt below in the terminal that will run the code. An agent can load the same variable from its secret store.

Set the key
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY

1. Create the search function

Save as search.mjs in your project folder. One call returns up to five web results, their URLs and actual usage. The function validates input, preserves result order, removes duplicate URLs and keeps the key out of the returned data. The 500-character limit is an app choice.

search.mjs
// search.mjs — server only; Node.js 22+
export async function searchWeb(query) {
  if (typeof query !== "string" || !query.trim() || query.length > 500) {
    throw Object.assign(new Error("Enter a query of 1–500 characters."), { status: 400 });
  }
  const apiKey = process.env.FLASHDATA_API_KEY;
  if (!apiKey) throw new Error("Set FLASHDATA_API_KEY on the server.");
  let response;
  try {
    response = await fetch("https://data.flashdata.dev/v1/queries/realtime", {
      method: "POST", redirect: "error", signal: AbortSignal.timeout(70000),
      headers: { "X-API-Key": apiKey, "Content-Type": "application/json" },
      body: JSON.stringify({ source: "google_search", query: query.trim(),
        params: { num: 5, gl: "us", hl: "en" } }),
    });
  } catch {
    throw new Error("Search outcome unknown. Check FlashData History before retrying.");
  }
  if (!response.ok) {
    throw Object.assign(new Error("Search failed: HTTP " + response.status), {
      status: response.status, retryAfter: response.headers.get("retry-after"),
    });
  }
  const data = await response.json();
  if (data.status !== "done" || !Array.isArray(data.results)) {
    throw new Error("Search did not finish. Check FlashData History.");
  }
  const seen = new Set();
  const sources = [];
  for (const [index, item] of (data.results[0]?.organic ?? []).entries()) {
    let url;
    try { url = new URL(item.link); } catch { continue; }
    if (!["https:", "http:"].includes(url.protocol) || seen.has(item.link)) continue;
    seen.add(item.link);
    sources.push({ rank: item.position ?? index + 1, title: item.title ?? item.link,
      url: item.link, snippet: item.snippet ?? "" });
  }
  return { query: query.trim(), sources, usage: data.usage,
    retrievedAt: new Date().toISOString() };
}

2. Add a local backend

Save as server.mjs beside search.mjs. GET /search?q=... calls the function; GET / serves the form you will create next. The server listens only on 127.0.0.1.

server.mjs
// server.mjs — local demo; keep your existing app's authentication in production.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { searchWeb } from "./search.mjs";

createServer(async (req, res) => {
  const url = new URL(req.url, "http://127.0.0.1:8787");
  res.setHeader("Cache-Control", "no-store");
  try {
    if (req.method === "GET" && url.pathname === "/") {
      const html = await readFile(new URL("./index.html", import.meta.url));
      res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
      return res.end(html);
    }
    if (req.method !== "GET" || url.pathname !== "/search") {
      res.writeHead(404); return res.end("Not found");
    }
    const result = await searchWeb(url.searchParams.get("q"));
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(result));
  } catch (error) {
    if (error.retryAfter) res.setHeader("Retry-After", error.retryAfter);
    res.writeHead(error.status ?? 502, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: error.message }));
  }
}).listen(8787, "127.0.0.1", () => console.log("Open http://127.0.0.1:8787"));

3. Display results in your app

Save as index.html in the same folder. This form handles loading, empty results and errors. It calls your backend and inserts snippets as text, so neither the API key nor external HTML reaches the page.

index.html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web search</title>
<h1>Search the web</h1>
<form id="search">
  <label>Query <input name="q" required maxlength="500" value="battery recycling research"></label>
  <button>Search</button>
</form>
<p id="status" role="status"></p>
<ol id="results"></ol>
<script type="module">
const form = document.querySelector("#search");
const status = document.querySelector("#status");
const results = document.querySelector("#results");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  form.querySelector("button").disabled = true;
  results.replaceChildren(); status.textContent = "Searching…";
  try {
    const q = new FormData(form).get("q");
    const response = await fetch("/search?q=" + encodeURIComponent(q));
    const data = await response.json();
    if (!response.ok) {
      const retryAfter = response.headers.get("Retry-After");
      throw new Error(data.error + (retryAfter ? " · Retry-After: " + retryAfter : ""));
    }
    for (const source of data.sources) {
      const li = document.createElement("li");
      const link = document.createElement("a");
      link.href = source.url; link.textContent = source.title;
      const excerpt = document.createElement("p");
      excerpt.textContent = source.snippet;
      li.append(link, excerpt); results.append(li);
    }
    const credits = data.usage?.credits ?? "not reported";
    status.textContent = (data.sources.length
      ? data.sources.length + (data.sources.length === 1 ? " source" : " sources")
      : "No matching pages. Try a broader query.") + " · Credits used: " + credits;
  } catch (error) { status.textContent = error.message; }
  finally { form.querySelector("button").disabled = false; }
});
</script>
</html>

4. Run your first search

Run from flashdata-search-demo in the terminal where you set the key. Open the URL and click Search once. Each submit makes a paid query; opening the page or editing the input makes none. Stop the local server with Ctrl+C when finished.

  1. Enter a specific topic, such as battery recycling recovery rates.
  2. Expect linked titles, snippets and the credits returned in usage.credits. Results vary; zero sources is a valid completed search.
In flashdata-search-demo · keep this terminal running
node server.mjs
Open in your browser
http://127.0.0.1:8787

The result your app receives

Abbreviated shape; URLs and usage below are illustrative. A search returns snippets and links. Use a page reader when your feature needs the full page text.

GET /search?q=...
{
  "query": "battery recycling research",
  "sources": [
    {
      "rank": 1,
      "title": "Example source",
      "url": "https://example.org/research",
      "snippet": "A returned search excerpt."
    }
  ],
  "usage": {
    "credits": 0.02
  },
  "retrievedAt": "2026-11-04T00:00:00.000Z"
}

Reuse search in an agent tool

Optional: save search-tool.mjs beside search.mjs. The runner accepts only search_web and its query. Create one runner per task and keep it across that task's model turns; maxCalls limits attempted searches, including failed attempts. It does not set a credit spending limit.

flashdata-search-demo/search-tool.mjs
// search-tool.mjs — one runner per task, reused across its model turns.
import { searchWeb } from "./search.mjs";

export const searchTool = {
  name: "search_web",
  description: "Find ranked web URLs and snippets for a focused query.",
  inputSchema: {
    type: "object", additionalProperties: false,
    properties: { query: { type: "string", minLength: 1, maxLength: 500 } },
    required: ["query"],
  },
};
export function createSearchToolRunner({ maxCalls = 2 } = {}) {
  if (!Number.isSafeInteger(maxCalls) || maxCalls < 1) {
    throw new Error("maxCalls must be a positive integer.");
  }
  let attempts = 0;
  return async function runTool(name, args) {
    if (name !== searchTool.name) throw new Error("Unknown tool: " + name);
    if (!args || typeof args !== "object" || Array.isArray(args) ||
        Object.keys(args).some(key => key !== "query") ||
        typeof args.query !== "string" || !args.query.trim() || args.query.length > 500) {
      throw new Error("Expected only query: a string of 1–500 characters.");
    }
    if (attempts >= maxCalls) throw new Error("Search call limit reached for this task.");
    attempts++; // Reserve before awaiting; a failed attempt still counts.
    return searchWeb(args.query);
  };
}

Try the tool directly

Save tool-demo.mjs in flashdata-search-demo, then run the command below from that folder with the same API key. This optional check makes one additional FlashData query without calling a model. Expect JSON with query, sources, usage and retrievedAt—the same result shape as the form.

flashdata-search-demo/tool-demo.mjs
// tool-demo.mjs — one direct tool call; no model-provider dependency.
import { createSearchToolRunner, searchTool } from "./search-tool.mjs";

if (process.argv.length !== 3) {
  console.error('Usage: node tool-demo.mjs "your search query"');
  process.exit(1);
}
const runTool = createSearchToolRunner({ maxCalls: 1 });
const result = await runTool(searchTool.name, { query: process.argv[2] });
console.log(JSON.stringify(result, null, 2));
Run once from flashdata-search-demo
node tool-demo.mjs "battery recycling research"

Connect it to your model

The demo exercises the tool function. Your framework supplies the model connection and message loop. Search returns links and snippets; read selected pages before using their full content in an answer. For resumed or distributed tasks, persist the attempt count and results with the task ID.

  1. Register searchTool.name, description and inputSchema using your framework's tool-definition format. Keep the API key in the backend environment.
  2. At task start, call createSearchToolRunner({ maxCalls: 2 }). For each model tool call, parse its JSON arguments and pass the name and parsed object to that same runner. Reject invalid JSON before dispatch.
  3. Return the JSON result to the model as a tool result with the original call ID. Preserve sources[].url for citations. If execution fails or reaches the limit, return the error; do not create a new runner to retry it.

Handle failures and ship it

For deployment, move /search behind your application's sign-in and per-user limits. Keep the API key in server configuration, retain usage with the request and render external content as text. Realtime is suited to this interactive form; use async for background work.

SituationApp behavior
ERR_MODULE_NOT_FOUND / ENOENTKeep all files in flashdata-search-demo and run from that folder. Save index.html before opening the page.
EADDRINUSEPort 8787 is occupied. Stop your earlier demo process before starting another.
Search call limit reachedThe task used its allowed attempts. Finish with the collected evidence or report the limit; creating a new runner would reset the count.
Empty resultsShow an empty state and let the user refine the query; do not retry automatically.
401 / 403 / 402Check the server key, google_search permission and account credits.
429Wait for Retry-After when provided; limit requests per user before calling FlashData.
Timeout / network errorShow an uncertain outcome. Inspect History before sending the same paid query again.