Home / Articles / Blog

Build a Google AI Overview API with Hono and OpenRouter (and Watch What Google's AI Says About Your Keywords)

Build a Google AI Overview API with Hono and OpenRouter (and Watch What Google's AI Says About Your Keywords)

Build a Hono API that returns Google's recent search results plus AI Overview and AI Mode answers, then uses an OpenRouter LLM to write an SEO brief. Tested code, costs and legal notes.

AIShrey Vijayvargiya

Build a Google AI Overview API with Hono and OpenRouter (and Watch What Google's AI Says About Your Keywords)

It's 9:40 on a Tuesday. A client messages you: "Our best article just lost its traffic. Google answers the question at the top now. Are we in that answer or not?"

So you open Google, type the query, squint at the AI box, and screenshot it. Then you do the same for the other 39 keywords on the list. Then again from another country. Then again next week to see whether anything moved.

By Thursday you have a folder of screenshots and no way to answer the question that matters: did we get cited, and who replaced us?

Screenshots don't scale and they don't diff. An API does. This post builds one: a small Hono service that returns Google's recent results and its AI answers in one clean shape, counts citations in plain code, and asks an LLM on OpenRouter to turn the facts into an SEO brief.

[ADD YOUR STORY: one real moment where checking AI answers by hand got old, ideally from your own AEO/GEO experiments. Two or three sentences. Delete this line if you'd rather keep the scenario above.]

Why bother? Because the ground has moved under organic rankings, and not in a straight line:

  • Ahrefs compared 300,000 keywords and found the top-ranking page gets about 58% lower click-through when an AI Overview shows, comparing desktop data from December 2023 with December 2025.
  • Seer Interactive's 2026 update tracked 5.47 million queries across 53 brands. Organic CTR on AI Overview queries bottomed near 1.3% in December 2025, then rebounded to about 2.4% by February 2026.

Two studies, two methods, two different shapes. The only safe conclusion is that the AI answer is now part of your SERP, it changes, and you need to measure it yourself.

If you read our earlier playbook on AI search visibility, this is the tooling that makes experiment 5 (track it separately) practical. If not, the ihatereading.in blog has the background.

The quick answer

If you only read one table, read this one.

If you need...UseWhy
Google's AI Overview and AI Mode as JSONDataForSEOAI Overview on the organic endpoint, AI Mode on its own endpoint
A second source you can swap inSerpApiTwo-step AI Overview flow; AI Mode is not covered in this adapter
A parseable SEO brief, not proseOpenRouter + strict JSON schemaOne key, many models, require_parameters keeps the schema honest
Citation counts you can trustPlain codeA domain match is a string comparison, not an opinion
To try it for freeMock providerTwo fake days of data, so /v1/changes shows a real diff
To skip the typingClaude Code + one promptSection "Skip the typing" below

What we're building

Five endpoints behind one API key:

EndpointWhat it answers
POST /v1/serpWhat are the organic results (optionally from the last hour/day/week) and what does the AI Overview say?
POST /v1/ai-answerJust the AI answer (AI Overview or AI Mode) and the pages it cites
POST /v1/briefIs my domain cited, where do I rank, and what should I do about it?
POST /v1/monitorSame citation check for up to 25 keywords at once
POST /v1/changesWhat moved since the last time I asked?

The design rule that shapes everything: code counts, the model interprets. Whether your domain appears in the citation list is a string comparison, not an opinion. Why the AI chose those sources is an opinion, and that's where the LLM earns its tokens.

I'd rather you rent the data than scrape Google yourself. Two providers cover the surfaces we need, and both are documented well enough to write adapters against:

AI OverviewAI ModeRecent-results filter
DataForSEOYes, as an ai_overview item on the organic endpoint (set load_async_ai_overview)Yes, dedicated endpointsearch_param with &tbs=qdr:d
SerpApiYes, two-step flow with a page_tokenNot covered in this adaptertbs=qdr:d

A Geekflare roundup also lists Apify and cloro as supporting both AI Overview and AI Mode, if you want alternatives. Treat that as a third-party summary and check each vendor's docs.

The legal part, plainly. Google sued SerpApi in December 2025, alleging it circumvents protections and ignores crawling rules. A Parallel write-up tracking the case says that as of October 30, 2026 the court had dismissed Google's two DMCA claims in July (some with leave to amend), Google had filed an amended complaint, and a second motion to dismiss was still pending. I haven't checked those against the docket, and the case may have moved since. I'm not a lawyer and this isn't legal advice. If SERP data feeds a paid product, read your provider's terms, ask counsel, and make the provider swappable, which is exactly why we build an adapter layer.

Setup

bash
mkdir serp-brief-api && cd serp-brief-api
npm init -y
npm i hono @hono/node-server @hono/zod-validator zod openai
npm i -D typescript tsx @types/node

Versions this was built and tested with: Hono 4.13, @hono/zod-validator 0.9, Zod 4.6, OpenAI SDK 7.68, TypeScript 7.0 and Node 22. We use the OpenAI SDK only as an HTTP client, because OpenRouter speaks the same protocol.

New to Hono? Read our Getting Started with Honojs first: it takes you from npm init to your first routes in a few minutes, then come back here. If you'd like to see how far one Hono file can go before you split it up, our single-file Hono scraping API is the same idea at a smaller scale.

One shape for every provider

Providers disagree on everything: field names, nesting, how citations are attached. Normalize once at the edge and the rest of the app never knows which vendor it's talking to.

ts
// src/types.ts (excerpt)
export interface Citation { url: string; domain: string; title: string; snippet: string }

export interface AiAnswer {
  surface: "ai_overview" | "ai_mode";
  markdown: string;
  sources: Citation[];
}

export interface SerpProvider {
  readonly name: string;
  serp(q: SerpQuery): Promise<{ organic: OrganicResult[]; aiOverview: AiAnswer | null }>;
  aiMode?(q: SerpQuery): Promise<AiAnswer | null>; // optional: not every vendor has it
}

aiMode is optional on purpose. If a provider doesn't support it, the API returns a clear 501 instead of pretending.

Adapter 1: DataForSEO

The documented request goes to /v3/serp/google/organic/live/advanced with Basic auth. The response path is tasks[0].result[0].items, and DataForSEO's success code is 20000 (the full list is on their errors page).

ts
// src/providers/dataforseo.ts (excerpt)
async function call(path: string, task: Json): Promise<Json[]> {
  const res = await f(`${base}${path}`, {
    method: "POST",
    headers: { Authorization: auth, "Content-Type": "application/json" },
    body: JSON.stringify([task]),
  });
  if (!res.ok) throw new ProviderError(`DataForSEO HTTP ${res.status}`);
  const json = (await res.json()) as Json;
  if (json.status_code !== OK) throw new ProviderError(`DataForSEO: ${json.status_message ?? json.status_code}`);
  const t = json.tasks?.[0];
  if (!t || t.status_code !== OK) throw new ProviderError(`DataForSEO task: ${t?.status_message ?? "no task returned"}`);
  return (t.result?.[0]?.items as Json[] | undefined) ?? [];
}

Two details worth knowing before you spend money:

  • load_async_ai_overview must be true to get overviews that Google generates asynchronously. Without it, the ai_overview item is null when no cached version exists. The docs list an extra $0.002 per use.
  • "Recent results" is a second request. Time filters go in search_param as &tbs=qdr:h (hour), d (24 hours), w, m or y. I fetch the AI answer from an unfiltered request, so it matches what a normal searcher sees, and the organic list from the filtered one. That's a design choice, and it means freshness costs two requests.
ts
async serp(q) {
  const aiTask = { ...baseTask(q), depth: q.freshness ? 10 : q.depth, load_async_ai_overview: true };
  const aiItemsP = call("/v3/serp/google/organic/live/advanced", aiTask);

  let organicItems: Json[];
  let aiItems: Json[];
  if (q.freshness) {
    const orgTask = { ...baseTask(q), depth: q.depth, search_param: `&tbs=qdr:${QDR[q.freshness]}` };
    [aiItems, organicItems] = await Promise.all([aiItemsP, call("/v3/serp/google/organic/live/advanced", orgTask)]);
  } else {
    aiItems = await aiItemsP;
    organicItems = aiItems;
  }
  return { organic: parseOrganic(organicItems, q.depth), aiOverview: parseAiItems(aiItems, "ai_overview") };
}

AI Mode uses /v3/serp/google/ai_mode/live/advanced, returns the same item shape, and exposes citations as references with source, domain, url, title and text. One catch from that page: AI Mode doesn't expose its fan-out query strings. Other DataForSEO endpoints do, which becomes idea #5 below.

Adapter 2: SerpApi

SerpApi's AI Overview is a two-step dance. The first search may return only a page_token instead of the overview. You exchange the token on a second engine call, and it expires within about four minutes. That's why we send no_cache=true on the first call: a cached response can carry an already-dead token.

ts
// src/providers/serpapi.ts (excerpt)
const params: Record<string, string> = {
  engine: "google", q: q.keyword, gl: q.country, hl: q.language,
  device: q.device, num: String(q.depth),
  no_cache: "true", // cached responses can carry an expired page_token
};
if (q.freshness) params.tbs = `qdr:${QDR[q.freshness]}`;

const json = await get(params);
let ai: Json | undefined = json.ai_overview;

if (ai?.page_token) {
  const follow = await get({ engine: "google_ai_overview", page_token: String(ai.page_token) });
  ai = follow.ai_overview;
}

The overview itself arrives as text_blocks (heading, paragraph, list, and lists can nest) plus a flat references array, as SerpApi documents. We flatten blocks into markdown. Their article says the block list isn't exhaustive, so the converter skips unknown types, tables included, instead of crashing. If you need tables, add a case when you meet one.

Count in code, interpret with an LLM

Everything an SEO person needs to count is deterministic. Here are the three helpers that matter.

Strip the highlight fragment. DataForSEO notes that cited URLs often end in a #:~:text= fragment. Left in, the same page looks like three different pages.

ts
// src/analysis.ts (excerpt)
export function cleanUrl(url: string): string {
  const i = url.indexOf("#:~:text=");
  const noFragment = i === -1 ? url : url.slice(0, i);
  return noFragment.replace(/\/$/, "");
}

export function domainMatches(domain: string, target: string): boolean {
  const d = normalizeDomain(domain);
  const t = normalizeDomain(target);
  return d === t || d.endsWith(`.${t}`); // blog.example.com counts for example.com
}

Build the citation report. It answers the client's Tuesday-morning question without a single model call: is the target in the AI Overview, is it in AI Mode, where does it rank organically, and which domains get cited most.

ts
{
  aiOverviewPresent: true,
  targetCitedInAiOverview: false,
  targetOrganicPosition: 3,
  topCitedDomains: [{ domain: "hono.dev", count: 1 }, { domain: "example-blog.com", count: 1 }],
  citedAndRankingDomains: ["hono.dev", "example-blog.com"]
}

Diff two snapshots. This is the feature screenshots can never give you: which results entered, dropped or moved, whether the overview appeared or vanished, and which sources were added or removed. It compares answer text after stripping citation markers like [1] and [[2]], so a renumbered citation doesn't count as a rewrite.

The OpenRouter call

Now the interpretation layer. We want a brief we can parse, not prose we have to scrape. OpenRouter supports structured outputs via response_format with a JSON schema. Two things from their docs matter:

  1. Support is decided per provider endpoint, not per model. Without a constraint, your request can be routed to a provider that quietly ignores your schema.
  2. The fix is provider: { require_parameters: true }.

We define the schema once in Zod and derive the JSON schema from it, so the types, the model's instructions and the runtime check can't drift apart.

ts
// src/llm.ts (excerpt)
export const BriefSchema = z.object({
  answerSummary: z.string().describe("2-3 sentences: what Google's AI answer tells the searcher"),
  searchIntent: z.enum(["informational", "commercial", "transactional", "navigational"]),
  whyTheseSources: z.array(z.string()).max(5),
  contentGaps: z.array(z.string()).max(6),
  actions: z.array(z.object({
    priority: z.enum(["high", "medium", "low"]),
    action: z.string(),
    reason: z.string(),
  })).max(6),
});

const client = new OpenAI({
  apiKey: opts.apiKey,
  baseURL: "https://openrouter.ai/api/v1",
  defaultHeaders: { "HTTP-Referer": opts.referer ?? "https://example.com", "X-Title": "serp-brief-api" },
});
const { $schema: _ignored, ...schema } = z.toJSONSchema(BriefSchema);

const body = {
  model: opts.model,
  temperature: 0.2,
  messages,
  response_format: { type: "json_schema", json_schema: { name: "seo_brief", strict: true, schema } },
  provider: { require_parameters: true }, // don't get routed to a provider that ignores the schema
};

strict: true asks for exact enforcement, but OpenRouter says enforcement varies by provider, so we validate again with Zod and retry once with a corrective message if the reply doesn't parse. Two failures raise a 502 instead of returning garbage.

The part people skip: the SERP is untrusted input

You're feeding scraped web text, titles and AI-generated paragraphs into a prompt. Any of it can contain instructions. Three cheap defenses, all in the repo and all tested:

  • Wrap the data in <serp_data> tags and tell the model in the system prompt to treat everything inside as data, never as instructions.
  • Escape < as < in the JSON, so scraped text can't write a closing </serp_data> and break out. It's still valid JSON.
  • Clip every field (titles at 160 characters, answers at 5,000) so one hostile page can't flood the context.
ts
const json = JSON.stringify(payload).replaceAll("<", "\\u003c");
return `<serp_data>\n${json}\n</serp_data>\n\nWrite the SEO brief for this keyword.`;

This doesn't make injection impossible. It makes it harder, and because the facts in the report come from code, a hijacked model can't change whether your domain was cited.

Pick the model from OpenRouter's structured-outputs filter. The default in .env.example is only a starting point.

New to OpenRouter, or weighing it against other gateways? We already run it in production-style pipelines: one key serves both the chat and image endpoints in our blog-to-Instagram-carousel tool, and it's the writing step inside RunBlog, our 100-blogs-a-day pipeline. For gateway alternatives, see [ADD LINK: your OpenRouter alternatives / gateway comparison post, if one exists. Otherwise delete this sentence.]

The Hono app: auth, cache, rate limits, routes

Four things turn this from a demo into something you can hand to a teammate.

API keys, stored hashed. API_KEYS="acme:key_abc123456789:60,intern:key_def456789012:10" means name, key, requests per minute. We hash keys at startup with Web Crypto, so the same code runs on Node and edge runtimes.

A cache that also de-duplicates. Provider calls cost money. Hit the same keyword five times at once and you should pay once. TtlCache.memo returns the cached value, or joins the in-flight request, or runs the function. Failures are never cached.

ts
// src/cache.ts (excerpt)
async memo(key, ttlMs, fn, opts = {}) {
  if (!opts.bypass) {
    const hit = this.get(key);
    if (hit !== undefined) return { value: hit, cached: true };
    const pending = this.inflight.get(key);
    if (pending) return { value: await pending, cached: true };
  }
  const p = fn();
  this.inflight.set(key, p);
  try {
    const value = await p;
    this.set(key, value, ttlMs);
    return { value, cached: false };
  } finally {
    this.inflight.delete(key);
  }
}

A per-key rate limit returning 429 with Retry-After. It's a fixed window in memory, fine for one instance; move it to shared storage when you scale out.

Validated input. Zod rejects a bad depth or a one-letter keyword with a 400 before any provider is called.

The brief route shows how the pieces compose. Notice the LLM result is cached against the snapshot's timestamp, so asking twice about the same data costs one model call.

ts
// src/app.ts (excerpt)
v1.post("/brief", zValidator("json", briefBody), async (c) => {
  const b = c.req.valid("json");
  const p = pickProvider(b.provider);
  const q = toQuery(b);
  const snap = await getSnapshot(p, q, b.refresh);
  const mode = b.includeAiMode ? await getAiMode(p, q, b.refresh) : undefined;
  const aiMode = mode?.value ?? null;
  const report = citationReport(snap.value, b.targetDomain, b.includeAiMode ? aiMode : undefined);

  const briefKey = ["brief", deps.llm.model, keyOf(p, q), snap.value.fetchedAt, b.targetDomain ?? "-", b.includeAiMode].join("|");
  const brief = await briefs.memo(briefKey, ttl, () =>
    deps.llm.brief({ keyword: b.keyword, target: report.target, organic: snap.value.organic,
                     aiOverview: snap.value.aiOverview, aiMode, report }));
  return c.json({ report, brief: brief.value, snapshot: snap.value, aiMode, meta: { provider: p.name, model: deps.llm.model } });
});

And /v1/monitor runs up to 25 keywords through a small worker pool so you don't hammer your provider. One failing keyword is reported on its own row, not as a failed batch:

ts
async function mapPool<T, R>(items: T[], limit: number, fn: (t: T, i: number) => Promise<R>): Promise<R[]> {
  const out = new Array<R>(items.length);
  let next = 0;
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
    for (;;) {
      const i = next++;
      if (i >= items.length) return;
      out[i] = await fn(items[i] as T, i);
    }
  });
  await Promise.all(workers);
  return out;
}

Run it without paying for anything

The repo includes a mock provider with two "days" of fake data, so you can build against the API and test /v1/changes before buying a single SERP call.

bash
export API_KEYS="me:demo-key-1234567890:60" PROVIDER=mock
npm start

curl -s -X POST localhost:8787/v1/monitor \
  -H "authorization: Bearer demo-key-1234567890" -H "content-type: application/json" \
  -d '{"keywords":["hono api","best hono tutorial"],"targetDomain":"mytarget.com"}'

Against the mock, that returns a summary like this (fake data, real code path):

json
{ "total": 2, "failed": 0, "withAiOverview": 2, "citedInAiOverview": 1, "rankingOrganic": 2 }

Call /v1/changes twice for the same keyword. The first call is a baseline ("baseline": true). The second returns the diff: a new organic result entering, one dropping, one moving up, and mytarget.com appearing in the AI answer's sources.

The repo ships 30 offline tests. They pass with no network and no keys. They check the exact HTTP request each adapter sends (URL, auth header, body fields, query parameters), the two-step SerpApi flow, the OpenRouter request shape, auth failures, validation errors, cache de-duplication, the 429 path, partial batch failures and the injection defenses.

One honest limit. The test fixtures are written from the providers' documented response shapes, not captured from live accounts. Before you trust it with real money, run one live request per provider and compare the real JSON with the adapter. I'd expect to adjust a field name or two on first contact. That's what the adapter layer is for.

What it costs

DataForSEO's AI Mode pricing page lists, per results page: Standard $0.0012, Priority $0.0024, Live $0.004 (page read on December 2, 2026, and it carries no date, so check it). Standard has a target turnaround of 45 minutes, Priority about a minute and Live about six seconds. The async AI Overview option on the organic endpoint adds $0.002 per use, per the docs. I did not confirm the base price of the organic endpoint, so look that up before budgeting.

Monthly cost for the AI Mode surface alone:

WorkloadRequests/monthStandardPriorityLive
100 keywords, daily3,000$3.60$7.20$12.00
250 keywords, weekly1,000$1.20$2.40$4.00

Add the $0.002 async-overview surcharge per request if you also pull AI Overviews through the organic endpoint (that's $6.00 and $2.00 on those two workloads), plus the organic base price, plus LLM tokens for /v1/brief.

Three ways to keep the bill down:

  1. Cache for an hour or more. AI answers don't change minute to minute. The default is one hour (CACHE_TTL_SECONDS).
  2. Use /v1/monitor for the daily check and /v1/brief only when something changed. The model call is the optional part.
  3. Use the Standard queue for scheduled jobs. Nobody is waiting on a nightly run.

Nine ways to expand it

  1. Schedule it. A cron trigger runs /v1/changes for your keyword list nightly and stores results in SQLite, D1 or Postgres. The SnapshotStore interface has two methods, so the swap is small.
  2. Alert on loss. Post to Slack or email when sourcesRemoved contains your domain. A lost citation is a better alarm than a rank drop.
  3. Feed it from Search Console. Pull queries that already earn impressions, as in experiment 4 of our playbook, and use them as the monitor list. You'll track the keywords you already win or nearly win.
  4. Turn gaps into posts. When /v1/brief lists content gaps, feed them into a pipeline like RunBlog, where each row is one researched query rather than a single mega-prompt.
  5. Share-of-voice. Across 200 keywords, what percentage of AI answers cite you versus each competitor? One loop over /v1/monitor results gives you a number a client understands.
  6. Fan-out queries. AI Mode doesn't expose them, but DataForSEO says its LLM Responses and LLM Mentions endpoints return a fan_out_queries array. Those are the sub-searches the model ran, which is a content brief in itself.
  7. Wrap it in an MCP server. Then Claude or any MCP client can ask "are we cited for this?" without a dashboard.
  8. Multi-market. The adapter already accepts country, language, device and a locationCode override. Loop over markets for international sites.
  9. Run it on the edge. Everything except the Node server entry uses Web APIs, so the same createApp can run on Cloudflare Workers. The repo only ships the Node entry, so treat the Workers port as yours to verify.

Gotchas I'd rather you hit here than in production

  • AI answers aren't deterministic. The same keyword can give different answers by run, location and device. Treat one snapshot as a sample and watch the trend.
  • Tokens expire. SerpApi's page token lives about four minutes. Exchange it immediately, and skip the cache on the first call.
  • Fragment URLs inflate your counts. Strip #:~:text= before you compare.
  • Unknown block types vanish. Our converter skips them on purpose. Log them in production so you notice when Google adds a new one.
  • Don't let the model count. Models miscount citations and invent domains. Compute facts in code and give the model the numbers.
  • Never trust scraped text inside a prompt. See the injection section above.
  • Freshness costs double on DataForSEO. Two requests, as explained in section 5.
  • Check the terms. Both the provider's and, for anything commercial, the legal situation in section 2.

FAQ

Is there an official Google API for AI Overviews?

I didn't research that question specifically, so check Google's current developer documentation, because this area changes quickly. This tutorial uses SERP data providers, which is the route the two vendors above document.

What's the difference between AI Overview and AI Mode?

AI Overview is the summary box above the results on some searches. AI Mode is Google's separate conversational search surface. They can cite different sources for the same question, so track both if both matter to you.

How do I check if my site is cited in AI Overviews?

Send the keyword and your domain to /v1/brief or /v1/monitor. The report's targetCitedInAiOverview field is a plain domain match against the cited sources, so it never depends on a model's judgment.

Can I get recent Google results only, like the last 24 hours?

Yes. Pass freshness: "day". Under the hood that sends Google's tbs=qdr:d filter (through search_param on DataForSEO and tbs on SerpApi).

Why OpenRouter instead of calling one model directly?

One API key and one request format for many models, so you can swap the model by changing an environment variable. Just remember require_parameters, or a routed provider may ignore your JSON schema.

Will this work on Cloudflare Workers?

The app code uses Web-standard APIs, but I only ran the Node entry. Test the Workers port yourself before promising it.

Skip the typing: one prompt that makes Claude Code build all of this

Everything above fits in one prompt. Create an empty folder, start Claude Code in it, paste the block below, and let it build the same API on the same stack: Hono, Zod, OpenRouter, DataForSEO and SerpApi adapters, caching, auth, tests and a README.

A few honest notes before you paste:

  • It won't produce our files byte for byte. Treat the tests as the contract. If the typecheck is clean and the tests pass, the shape is right.
  • Step 0 makes it read the provider docs first. That's deliberate. Field names drift, and a prompt written today shouldn't overrule the docs tomorrow.
  • Keep keys out of the prompt. Put them in .env yourself, after the build. The prompt tells Claude Code not to call any paid API unless you've done that and said so.
  • Read the diff. You're about to run code that spends money and handles other people's search data. Skim the adapters and the auth middleware before you deploy.
text
You are a senior TypeScript engineer. Build a complete, tested API called "serp-brief-api" in the current (empty) directory. Work autonomously and only stop to ask me something if you are truly blocked.

WHAT IT DOES
An HTTP API for SEO teams. For a keyword it returns: (1) Google's organic results, optionally limited to the last hour/day/week/month/year; (2) Google's AI Overview and AI Mode answers as markdown plus the pages they cite; (3) a citation report computed in plain code; (4) an SEO brief written by an LLM through OpenRouter; (5) batch monitoring for up to 25 keywords; (6) change detection against the previous snapshot.

FIXED STACK
Node 22, TypeScript (strict, noUncheckedIndexedAccess, ESM with "type": "module", imports ending in .ts), Hono, @hono/node-server, @hono/zod-validator, Zod 4, the openai npm package pointed at OpenRouter (baseURL https://openrouter.ai/api/v1), tsx, node:test. No database and no other frameworks. Install the latest versions and list them in the README. Only src/server.ts may use Node-only APIs (process.env, the node server). Everything else must use Web-standard APIs (fetch, Web Crypto, btoa) so the app can later run on Cloudflare Workers.

STEP 0: VERIFY BEFORE YOU CODE
Read these docs and confirm field names and parameters. Where a doc disagrees with this prompt, trust the doc and record the difference under "Deviations" in the README.
- https://docs.dataforseo.com/v3/serp/google/organic/live/advanced/
- https://dataforseo.com/help-center/parse-google-ai-overviews-ai-mode
- https://dataforseo.com/help-center/google-search-engine-parameters-and-how-to-use-them
- https://serpapi.com/blog/fetching-ai-overviews-with-node-js/
- https://serpapi.com/blog/understanding-ai-overview-data-from-serpapi/
- https://openrouter.ai/docs/guides/features/structured-outputs

FILES
src/types.ts
  Normalized types: Freshness, Device, Surface, SerpQuery, Citation, OrganicResult, AiAnswer, SerpData, Snapshot, and SerpProvider (serp() plus an optional aiMode()). Also ProviderError (carries an HTTP status) and NotSupportedError (501).
src/analysis.ts
  normalizeDomain, cleanUrl (strip "#:~:text=" fragments and a trailing slash), domainMatches (subdomains count as a match), dedupeCitations, citationReport(data, targetDomain?, aiMode?) and diffSnapshots(prev, next). The diff reports organic results entered/dropped/moved, AI Overview presence (appeared, disappeared, present, absent), whether the answer text changed after stripping citation markers like [1] and [[2]], and sources added/removed.
src/cache.ts
  TtlCache with memo(key, ttlMs, fn, {bypass}). It returns cached values, joins identical in-flight requests, never caches failures, caps its size and accepts an injectable clock.
src/store.ts
  A SnapshotStore interface (get/put) and an in-memory implementation.
src/providers/dataforseo.ts
  POST /v3/serp/google/organic/live/advanced with Basic auth and body [{keyword, location_code, language_code, device, depth, load_async_ai_overview: true}]. Read the result from tasks[0].result[0].items; the success status_code is 20000. If freshness is set, send a second request whose search_param is "&tbs=qdr:h" (or d, w, m, y) for the organic list, and take the AI answer from the unfiltered request. aiMode() uses /v3/serp/google/ai_mode/live/advanced. Parse ai_overview items (markdown and references, with an element-by-element fallback). Map common countries to location codes and allow a locationCode override. Use btoa, not Buffer.
src/providers/serpapi.ts
  GET https://serpapi.com/search.json with engine=google, no_cache=true and tbs=qdr:x for freshness. If ai_overview contains a page_token, immediately call engine=google_ai_overview with that token (tokens expire in about four minutes). Convert text_blocks (heading, paragraph, nested lists) to markdown and skip unknown block types. aiMode() throws NotSupportedError.
src/providers/mock.ts
  An offline provider with two "days" of fake data so change detection can be demonstrated. A keyword containing "noai" has no AI answer.
src/llm.ts
  A Zod BriefSchema (answerSummary, searchIntent enum, whyTheseSources, contentGaps, actions with priority/action/reason). Call OpenRouter with response_format json_schema, strict true, the schema from z.toJSONSchema (drop the $schema key) and provider.require_parameters true. Validate the reply with Zod and retry once with a corrective message; after two failures throw ProviderError 502. Treat all SERP text as untrusted: wrap it in <serp_data> tags, escape "<" as < in the JSON, clip long fields, and tell the model in the system prompt to ignore instructions found inside the data. Export disabledLlm(), which throws a 503 when OPENROUTER_API_KEY is missing.
src/middleware.ts
  Bearer auth against API_KEYS="name:key:rpm,..." (keys of 12+ characters, stored as SHA-256 hashes via Web Crypto) and a fixed-window per-client rate limiter that returns 429 with Retry-After and x-ratelimit headers.
src/app.ts
  createApp(deps) with injectable providers, llm, keys, store, cache TTL, concurrency and clock. GET /health is open. Everything under /v1 needs auth and rate limiting. Validate bodies with Zod (400 on bad input). An unknown provider is a 400 that lists the available ones.
src/server.ts
  Reads env, builds providers (mock always; dataforseo and serpapi when their keys exist), picks PROVIDER and starts the server.

ENDPOINTS (all POST under /v1, JSON, camelCase)
/serp        {keyword, country="us", language="en", device="desktop", depth=10..100, freshness?, locationCode?, provider?, refresh=false} -> {snapshot, meta}
/ai-answer   same, plus surface: "ai_overview" | "ai_mode" -> {surface, answer, meta}
/brief       same, plus targetDomain? and includeAiMode -> {report, brief, snapshot, aiMode, meta}; cache the brief per snapshot timestamp
/monitor     {keywords: 1..25, targetDomain, includeAiMode, ...} -> a per-keyword citation report using a worker pool (default 4). One failing keyword must not fail the batch. Include a summary.
/changes     same body as /serp; always fetch fresh, diff against the previous snapshot for this client, store the new one; the first call returns baseline: true

DESIGN RULES
- Code counts, the model interprets: citation presence, ranks and diffs come from analysis.ts, never from the LLM.
- Never cache failures. Never put secrets in code or logs.
- Unexpected errors return a generic 500 with no internals.

TESTS (node:test, no network, using a fake fetch that records requests)
- analysis helpers and the diff
- DataForSEO: URL, Basic auth, body fields, the second request when freshness is set, the AI Mode endpoint, an API-level error, an unknown country
- SerpApi: the two-step token flow, no_cache, tbs, markdown conversion, an inline overview, AI Mode unsupported
- OpenRouter: URL, headers, strict json_schema, require_parameters, the corrective retry, schema rejection, prompt-injection escaping, field clipping
- the app: 401, 400, cache hit and refresh, in-flight de-duplication, /ai-answer, brief caching, /monitor with a partial failure, /changes baseline then diff, 429
Fixtures are written from the docs, not captured live. Say so in a comment at the top of the fixtures.

DELIVERABLES
package.json scripts (dev, start, typecheck, test), tsconfig.json, .env.example (API_KEYS, DATAFORSEO_LOGIN, DATAFORSEO_PASSWORD, SERPAPI_KEY, PROVIDER, OPENROUTER_API_KEY, OPENROUTER_MODEL, APP_URL, CACHE_TTL_SECONDS, CONCURRENCY, PORT), .gitignore, and a README with a quick start, an endpoint table, an env table, "Deviations" and a "What is verified" section.

DONE MEANS
- npm run typecheck is clean and npm test passes.
- Start the server with PROVIDER=mock, curl every endpoint, and show me the real output.
- Do not call any paid API unless I have put keys in .env and told you to. If I have, make one live request per provider and report how the real JSON differs from your fixtures.
- Never claim something was tested live unless you ran it live.
- Finish with a short summary of what you built, what you verified and what you did not.

Paste it, watch the first typecheck, and when the tests pass, run it against the mock server with the curl call from section 10.

So, where do you start?

Four ways to start, smallest first:

  1. Let Claude Code build it. Paste the prompt from section 15 into an empty folder and review what comes out.
  2. Run the mock in five minutes. Clone the repo, npm install, PROVIDER=mock npm start, then call /v1/changes twice. You'll see the whole loop without spending anything.
  3. Point it at your own keywords. Put one provider key in .env, add your domain, and run /v1/monitor on your ten most important queries. Reply with what surprised you, such as which competitor Google's AI cites instead of you.
  4. Want it built and hosted for your team? Karyam (karyam.xyz) takes on client builds like this. [CONFIRM or edit this offer before publishing.]

If you want the bigger picture, our monthly magazine covers AI search and SaaS growth, and the SaaS directories page lists places to get your product listed and cited.

Repo: [ADD LINK: github.com/shreyvijayvargiya/serp-brief-api, once pushed]

Sources: Ahrefs · Seer Interactive · DataForSEO organic docs · DataForSEO AI Overview and AI Mode guide · DataForSEO time filter · DataForSEO AI Mode pricing · SerpApi AI Overviews in Node · SerpApi AI Overview data · SerpApi time filtering · Google on the SerpApi suit · Parallel on scraping legality · OpenRouter structured outputs · Geekflare SERP API roundup · Hono docs

External Links (24)

Explore topics

More in

Weekly letter

Subscribe to iHateReading

Our once-a-week newsletter on programming, jobs, AI, and building products online.

Our once a week newsletter on Programming, Jobs, AI, and Business