The approach on this page no longer returns any data
This page documents how google-trends-scraper versions 0.1.x worked: a POST to the internal batchexecute endpoint with the RPC id i0OFE. That call now answers with a null payload, so the request shape, the response anatomy and the code samples below are kept for reference only and will not return trending searches. Version 0.2.0 reads the trending data inlined in the Trending Now page instead.
The current write-up — request flow, options, result fields, error model and limits — lives on the new site:
The official Google Trends API is still an alpha you have to apply for, so most teams end up using an unofficial client instead. google-trends-scraper is one: it reads the Trending Now board that trends.google.com itself uses and returns Google Trends data as typed objects — what is spiking in one country right now, how much it grew, and whether the trend is still running. This guide covers what the official API does and does not give you, how the scraper works under the hood, and how to call it in your own project.
The Trending Now board for any supported country or region
Search-volume tier, growth percentage, start and end time, category IDs
Local filtering by category and active/ended status, plus four sort modes
Typed results and a typed error class, with no runtime dependencies
What it is not
It is not an official Google API and carries no compatibility promise
It does not return Explore data: interest over time, by region or by query
It does not open a browser or parse HTML pages
It does not return exact search counts, only the tier shown on the page
Does Google Trends have an API?
Yes, and that is the whole problem: the official Google Trends API exists but is an alpha you apply for. It is not a key you can generate, and it is not the same data as the Trending Now board.
Access is an application, not a signup
Google announced the API in July 2025 and the page is still titled alpha. Access goes to a limited set of testers, prioritising developers who have a concrete use case and can give feedback. There is no self-serve key to request today.
It serves the Explore-style dataset
Google describes a rolling five-year window, daily to yearly aggregation, country and sub-region comparisons, and consistently scaled values that are no longer pinned to a 0–100 index. That is the interest-over-time dataset, not a live board of spiking searches.
Trending Now is a different product
The Trending Now board shows what is spiking in one country within a 4, 24, 48 hour or 7 day window. It is separate from Explore, and it is the dataset this package reads — which is why the two are not substitutes for each other.
What teams do while they wait for access
Without alpha access there are three realistic routes to Google Trends data: export a CSV by hand from the website, pay a hosted scraping vendor, or run an open-source client yourself. Only the last one is both free and automatable, and it is the trade-off this package takes: no key, no account, but also no compatibility promise from Google.
How to get Google Trends data: match the source to the question
“Get Google Trends data” means at least four different things. Decide which one you need first, because the source, the access route and the limits all change.
What you need
Where it comes from
Key required
Searches spiking in one country right now
The Trending Now board, read in a browser or programmatically by this scraper
No
Interest over time, and interest by region
The Explore section of trends.google.com, or the official API alpha if you are accepted
Application for the API, none for the UI
Related queries and topics
Explore. Expect the head of the list to be stable and the tail to move between page loads
No, but manual
Absolute search volume
Nowhere in Google Trends. It reports relative interest and tier floors, never a count of searches
—
A one-off CSV for a report
The download button in the Trends interface
No
Open-source Google Trends libraries, honestly compared
If you are looking for a library rather than an endpoint, this is the state of the field. The dates come from the npm registry, PyPI and GitHub, and are linked in the sources at the end of this page.
Client
Runtime
Covers
Status
google-trends-scraper (this page)
Node.js 22.13+
The Trending Now board only
Published and maintained, with zero runtime dependencies
google-trends-api
Node.js
Interest over time, interest by region, related queries and topics, daily and realtime trends
Last published December 2020. Treat it as unmaintained even though it still pulls hundreds of thousands of downloads a month
pytrends
Python
The same Explore-style endpoints, plus trending searches
Last PyPI release April 2023. The GitHub repository is archived and carries 150+ open issues
Varies by package, and some cover Explore rather than Trending Now
They exist and some are actively published. Check the last publish date and the open issue count yourself before adopting one
If you arrived here looking for a maintained pytrends alternative, or an alternative to the long-serving google-trends-api package, the same two questions decide it: which dataset you actually need, and whether the client is still being published. Everything else — stars, download counts, tutorials — is a lagging signal.
Disclosure: this page is written by the maintainer of google-trends-scraper, so weigh the comparison accordingly. Every date above can be checked independently at the linked sources.
Three questions before you pick one
Which dataset do you actually need? Trending Now and Explore are different products, and a client that covers one usually does not cover the other.
Is it still maintained? A library can be extremely popular and abandoned at the same time — the publish date is the honest signal, not the download count.
Does the runtime fit? Check the Node version, the dependency count, and whether the client needs a headless browser or can work over plain HTTP.
How the scraper works, step by step
One call to fetchTrendingNow runs five stages. Knowing them explains every option, every limit and every error code later in this guide.
1
Validate and normalise the options
Country code, interface language, time window, category, status, sort mode and limit are all checked before any network call. The language tag is canonicalised with Intl.getCanonicalLocales, the country code is upper-cased, and limit: "all" becomes Infinity only internally. A bad argument throws INVALID_ARGUMENT without touching the network.
2
Build a batchexecute request
The package posts to the same batch RPC endpoint the Trending Now page calls. The RPC id, source path and interface language travel in the query string; the arguments travel in an f.req form field wrapped in the envelope [[[rpcId, JSON.stringify(args), null, "generic"]]].
3
Send it with browser-like headers, under a timeout
The request carries content-type, origin, referer and a user-agent, because the endpoint is normally called by the page itself. An AbortController covers both the request and the body read, so a stalled download cannot hang a job. There is deliberately no automatic retry.
4
Find the RPC frame inside the chunked body
The response is not a single JSON document: it starts with an anti-XSSI prefix and repeats a length line plus a JSON array. The parser walks the text with a bracket-depth scanner that respects string escaping, picks the frame whose first field is wrb.fr and whose second field is the requested RPC id, then parses the payload string it carries.
5
Map rows to typed items, then filter locally
Rows are positional arrays, so each field is read by index and validated. Unix seconds become millisecond timestamps, ended == null becomes active: true, and news references are kept as id plus language and country. Filtering by category and status, the four sort modes and the final truncation all happen in memory, after which rank is renumbered from 1.
Why not scrape the HTML page instead?
The trending table on trends.google.com is rendered on the client, so it is not present in the HTML the server returns. Reading the same JSON endpoint the page itself uses avoids shipping a headless browser, keeps the response small and, most importantly, makes breakage detectable: an unexpected shape raises INVALID_RESPONSE instead of quietly returning zero rows.
What the request looks like
One POST with three query parameters and a single form field named f.req. That one field carries the entire call description, which is why it looks so dense.
That body is byte-for-byte what the package sends for { geo: "SG", hours: 24 }. It is percent-encoded because the content type is application/x-www-form-urlencoded, and it stays on one line — scroll the block sideways to read it. Decoded, the value is a nested array, and the endpoint expects exactly this shape.
What f.req actually contains
Read from the outside in: the outermost array is the batch, each entry in it is one call, and every call is [rpcId, argumentsAsJsonString, null, "generic"].
f.req, decoded
[
[
[
"i0OFE", // which endpoint to call
"[null,null,\"SG\",0,\"en\",24,1]", // the arguments, JSON-encoded as a string
null, // unused
"generic" // fixed marker
]
]
]
The arguments sit in the second slot, and they are a string rather than a nested array: the package runs JSON.stringify on them before embedding them. That is why you see \"SG\" with escaped quotes instead of plain "SG" — it is JSON inside JSON. Country, window and sort order travel as one encoded string, and the endpoint parses that string a second time on its side.
These ids are internal identifiers of the Trending Now page. They are not a documented contract, which is why the package treats an unexpected response shape as an error rather than as an empty result.
What comes back, and how it is read
The response body is a stream of length-prefixed frames with an anti-XSSI prefix, not one JSON document. Parsing it needs two passes.
http response
HTTP/1.1 200 OK
)]}'
<length>
[["wrb.fr","i0OFE","[null,[[\"query 1\",null,\"SG\",[1792416660],null,null,100,null,1000,…]]]"]]
<length>
[["di",17],["af.httprm",16,"<token>",25]]
The status line is there to make the boundary obvious: )]}' really is the first line of the response body, not a fragment that lost its beginning. Google prefixes JSON responses with it so the payload cannot be pulled in through a <script> tag and read by another page — the prefix makes the bytes invalid JavaScript on purpose. The blank line after it belongs to the response as well. The <length> lines and the trailing bookkeeping frames are endpoint housekeeping, and the parser skips all of them by design.
1
Scan for balanced JSON chunks
A bracket-depth scanner walks the text, ignoring brackets inside strings and honouring backslash escapes. It deliberately ignores the length lines, so a wrong or missing length prefix cannot desynchronise the parse.
2
Pick the frame for this RPC id
Each chunk is an array of frames. The parser keeps the one whose first element iswrb.fr and whose second element equals the requested RPC id, and ignores anything the frame carries after the payload. Frames whose payload is not a string raise INVALID_RESPONSE, which is the early warning that the endpoint changed.
3
Parse the payload string again
The third element of the frame is a JSON string that must be parsed a second time. The resulting payload holds the row array; for the country list it holds grouped country entries instead.
How a row index becomes a typed field
Index
Output field
How it is handled
0
query
Required. A row without a non-empty query is rejected.
2
geo (checked, not kept)
Must equal the requested country, otherwise the row is treated as malformed.
3
startedAtMs
The source sends Unix seconds inside a one-element array; the package converts to milliseconds.
4
endedAtMs, active
null means the trend is still running, which becomes active: true.
6
searchVolume
A tier floor, not an exact count: 5000 stands for the 5000+ bucket on the page.
8
increasePercentage
Passed through as returned by the source and never recalculated.
9
trendBreakdown
Related query strings for the same trend.
10
categoryIds
Numeric category ids, matched by the category option.
11
newsReferences
Only id, language and country — the source does not return usable article links.
12
normalizedQuery
Falls back to query when the source returns nothing usable.
Rows are positional arrays with a fixed layout. Every field the package exposes is read by index and validated, so a shift in the source layout surfaces as an error instead of silently mislabelled data.
What Google Trends data is actually useful for
Trending Now answers one narrow question well: what searches are spiking in this country right now. That single slice of Google Trends data feeds several jobs.
Editorial and content calendars
A trending query is a topic your audience is already typing today. It gives a writer a title that matches current demand instead of a guessed theme for next month.
Keyword discovery before volume tools catch up
Long-tail keyword tools report monthly averages and often add fast-rising queries days later. The Trending Now board shows the spike while it is still rising.
Per-market and localised content
Every request is scoped to one country or region, so the same editorial plan can be rewritten per market instead of translated from a US-centric list.
Newsroom and social monitoring
The 4-hour window exposes a spike before it reaches general reporting. Growth percentage and start time tell you whether a topic is accelerating or already fading.
Product and demand signals
Category IDs and the trend breakdown separate a product surge from a news surge, which is useful for stock, ads and landing-page decisions.
Always-on reporting pipelines
The response is plain JSON with stable field names, so a scheduled job can store history, diff it against yesterday and alert only when something new appears.
Read the numbers correctly
A trend is a spike against that country’s own baseline. It is not the same as a high absolute search volume, and a small market can show a trend for a query with modest traffic.
Search volume is a floor, not a count. The board stops at 5000+, so a value of 5000 means “at least 5000”, and ties at that value are expected.
Trends are short-lived. Most entries end within hours, which is why the ended timestamp and the active flag matter as much as the ranking itself.
There is no history curve here. For long-term demand, pair the trending list with a keyword tool that reports stable monthly volume.
Using the google-trends-scraper package
One function call returns the board. Install the scraper with your package manager of choice and await the result.
Node.js 22.13 or newer — the package uses the built-in fetch and AbortSignal and ships no polyfills.
No API key, no Google account and no headless browser to install.
TypeScript types are bundled, so no @types package is needed.
Run it on the server. The package sets its own origin and referer headers, which a browser would override, so browser-side calls are not supported.
A first request
trending.ts (ESM)
import { fetchTrendingNow } from 'google-trends-scraper';
const result = await fetchTrendingNow({
geo: 'SG', // country or region code
hours: 24, // 4, 24, 48 or 168
limit: 25, // default is 25, 'all' keeps everything returned
});
console.log(result.geo, result.total, result.filteredTotal);
for (const item of result.items) {
console.log(item.rank, item.query, item.searchVolume, item.increasePercentage);
}
The returned object echoes the options that actually took effect, so you never have to guess which defaults were applied. total is the size of the board the source returned; filteredTotal is how many rows survived your category and status filters before the limit was applied.
Country names come from a second RPC id, so you can build a picker or validate a user-provided market before requesting a board. Only the top-level menu is returned: states, provinces and the “your location” entry are excluded.
Every option is optional. Invalid values throw INVALID_ARGUMENT before any request is sent, so a typo fails fast instead of silently returning the wrong country.
Option
Type
Default
Behaviour
geo
string
'SG'
Two-letter country or region code. Validated by pattern and upper-cased before sending.
hl
string
'en'
Interface language for returned names. Canonicalised with Intl.getCanonicalLocales, so zh-cn becomes zh-CN.
hours
4 | 24 | 48 | 168
24
Time window for the board. Anything outside the four allowed values is rejected.
category
number
0
Category id to keep. 0 means all categories; other values are matched against each row’s category ids.
status
'all' | 'active' | 'ended'
'all'
Filters on whether the trend still has an end time. active means it is still running.
sort
'relevance' | 'volume' | 'recency' | 'title'
'relevance'
relevance keeps the order the source returned. The other three re-sort locally, and title sorting follows the hl locale.
limit
number | 'all'
25
Applied after filtering. all keeps every row the source already returned; it does not fetch more pages.
timeoutMs
number
30000
Covers the request and the body read. Must be an integer between 1 and 2147483647.
signal
AbortSignal
—
Optional caller-owned cancellation. An abort rejects with code ABORTED.
fetch
typeof fetch
globalThis.fetch
Injection point for a proxy-aware client or a test double.
The result wrapper and each item
fetchTrendingNow resolves to a TrendingNowResult. Besides items, it repeats the effective geo, hl, hours, category, status and sort, plus total and filteredTotal.
Field
What it holds
rank
Position in this result after filtering and truncation, starting at 1.
rawRank
Position on the source board, kept so you can tell a filtered list from the original.
query
The trending search text exactly as the board shows it.
normalizedQuery
Normalised form from the source, useful for de-duplicating near-identical entries.
searchVolume
Tier floor rather than a count: 5000 means the 5000+ bucket.
increasePercentage
Growth reported by the source, passed through unchanged.
startedAtMs
When the trend started, as a Unix millisecond timestamp ready for new Date().
endedAtMs
When it ended, or null while it is still active.
active
Shorthand for endedAtMs === null.
trendBreakdown
Related query strings grouped into the same trend.
categoryIds
Category ids the row belongs to; this is what the category option matches.
newsReferences
Article ids with a language and country. There are no article URLs in the payload.
Sorting by volume has ties
Because search volume is a tier floor, many rows share the same value. Sorting by volume therefore groups rows by bucket rather than producing a strict ranking inside a bucket. If you need a strict order, sort by startedAtMs or by increasePercentage in your own code after the call.
Recipes for real jobs
The package deliberately does one thing: fetch one board. These patterns cover what most projects build on top of it.
Build a daily content brief
Combine the status filter with the volume sort to keep only trends that are still running, then turn them into headlines.
brief.ts
import { fetchTrendingNow } from 'google-trends-scraper';
// One market, only trends that are still running, biggest bucket first.
const { items, geo } = await fetchTrendingNow({
geo: 'US',
hours: 24,
status: 'active',
sort: 'volume',
limit: 10,
});
const brief = items.map((item) => ({
headline: item.query,
growth: item.increasePercentage + '%',
startedAt: new Date(item.startedAtMs).toISOString(),
}));
Sweep several markets in one job
Each country is a separate request, so loop deliberately and leave a gap between calls instead of firing them all at once.
sweep.ts
const MARKETS = ['US', 'GB', 'SG', 'JP'];
// One request per market, run sequentially: there is no pagination to loop over.
for (const geo of MARKETS) {
const { items } = await fetchTrendingNow({ geo, hours: 24, limit: 10 });
console.log(geo, items.map((item) => item.query));
await new Promise((resolve) => setTimeout(resolve, 1000));
}
Alert only on genuinely new trends
A short window polled on a schedule repeats itself. Remember what you have already seen and report the difference.
diff.ts
const seen = new Map<string, number>(); // normalizedQuery -> first seen (ms)
const TTL_MS = 7 * 24 * 60 * 60 * 1000;
/** Returns only the trends this process has not reported before. */
async function pollOnce(geo: string) {
const { items } = await fetchTrendingNow({ geo, hours: 4, limit: 'all' });
const now = Date.now();
const fresh = items.filter((item) => !seen.has(item.normalizedQuery));
for (const item of fresh) seen.set(item.normalizedQuery, now);
for (const [query, firstSeen] of seen) {
if (now - firstSeen > TTL_MS) seen.delete(query);
}
return fresh;
}
Cap the time a request may take
A stalled request should not hold a job open. Pass your own signal as well as a timeout to keep cancellation under your control.
abort.ts
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10_000);
try {
const result = await fetchTrendingNow({
geo: 'SG',
timeoutMs: 8_000, // covers the request and the body read
signal: controller.signal,
});
console.log(result.items.length);
} finally {
clearTimeout(timer);
}
Observe or proxy the network call
The fetch option exists so you can log latency, run through a proxy agent, or replace the transport in tests.
observed-fetch.ts
import { fetchTrendingNow } from 'google-trends-scraper';
// Wrap the built-in fetch to log latency, or to route through a proxy agent.
const observedFetch: typeof fetch = async (input, init) => {
const started = Date.now();
const response = await fetch(input, init);
console.log('trends rpc', response.status, Date.now() - started + 'ms');
return response;
};
const result = await fetchTrendingNow({ geo: 'SG', fetch: observedFetch });
Errors you can branch on
Every failure is a GoogleTrendsError with a stable code, so you can decide between fixing the call, backing off and alerting.
Code
Raised when
Sensible reaction
INVALID_ARGUMENT
An option, the abort signal, the injected fetch or timeoutMs is not usable.
Fix the call. Retrying the same input cannot succeed.
HTTP_ERROR
The endpoint answered with a non-success status. Carries status and, when present, retryAfter.
Back off and honour retryAfter if the header was sent. Treat 429 and 5xx as rate limiting or an outage.
NETWORK_ERROR
The connection itself failed. The original error is preserved on cause.
Treat as transient. Retry later with a delay rather than immediately.
TIMEOUT
The request or the body read exceeded timeoutMs.
Raise timeoutMs for slow links, or retry later if the endpoint is slow for everyone.
ABORTED
Your own signal aborted the call.
Expected during shutdown or when a newer run replaces an older one. The abort reason is on cause.
INVALID_RESPONSE
The payload did not have the expected shape — an endpoint change, a different RPC frame, or an interstitial page.
Do not treat it as an empty result. Log it and check whether the response format moved.
handle-errors.ts
import {
GoogleTrendsError,
GoogleTrendsErrorCode,
fetchTrendingNow,
} from 'google-trends-scraper';
try {
const result = await fetchTrendingNow({ geo: 'SG' });
console.log(result.items.length);
} catch (error) {
if (!(error instanceof GoogleTrendsError)) throw error;
switch (error.code) {
case GoogleTrendsErrorCode.HttpError:
console.error('http', error.status, 'retry after', error.retryAfter ?? 'unspecified');
break;
case GoogleTrendsErrorCode.Timeout:
case GoogleTrendsErrorCode.NetworkError:
console.error('transient, back off before retrying');
break;
case GoogleTrendsErrorCode.InvalidResponse:
console.error('unexpected payload, the endpoint may have changed');
break;
default:
console.error(error.code, error.message);
}
}
The original failure is always kept on cause, so a logger can record the underlying socket error or abort reason without losing the package level context. There is no automatic retry inside the package: retrying a rate limit automatically is how a client turns a warning into a block.
retry-once.ts
/** The package never retries on its own; one explicit retry with a delay is usually enough. */
async function fetchWithOneRetry(geo: string) {
try {
return await fetchTrendingNow({ geo });
} catch (error) {
const isHttpError =
error instanceof GoogleTrendsError && error.code === GoogleTrendsErrorCode.HttpError;
if (!isHttpError) throw error;
// retryAfter is in seconds when numeric, but the header may also be an HTTP date.
const seconds = Number(error.retryAfter);
const waitMs = Number.isFinite(seconds) ? seconds * 1000 : 60_000;
await new Promise((resolve) => setTimeout(resolve, waitMs));
return await fetchTrendingNow({ geo });
}
}
Limits, and using it responsibly
The package is small because it refuses to pretend. These are the boundaries you should design around before shipping it into a product.
The endpoint is unofficial and can change
The RPC ids and the row layout belong to the Trending Now page, not to a published API. There is no deprecation notice and no version negotiation. Pin the package, keep an eye on INVALID_RESPONSE, and be ready to update rather than assume stability.
Only Trending Now is covered
Explore features — interest over time, interest by region, related queries, historical comparisons — are not part of this data source and are not simulated here. If a project needs those, this package is the wrong tool.
Volume is a bucket, not a number
The board reports tiers such as 5000+. Treat the value as a floor. Any calculation that needs real magnitudes has to come from somewhere else.
There is no pagination
limit: "all" keeps every row the source already returned; it does not request more pages. The board is a sample of what is spiking, not the complete set of searches in a country.
Rate limiting is your responsibility
The package sends one request per call, does not rotate proxies and does not retry automatically. Cache results, poll on a sensible interval, and never run an unbounded loop of markets.
It needs a runtime with global fetch
Node.js 22.13 or newer is the supported target, and the package ships no polyfills. Browsers are out of scope, because the request sets origin and referer headers that a browser will overwrite.
Before you ship it
Check that your use complies with Google’s terms and with local law, and do not present these numbers as official Google data.
Say where the data came from and when it was collected. Trending data without a timestamp is not verifiable.
The package is MIT licensed and provided as is, without warranty. The risk of relying on an undocumented endpoint sits with the caller.
google-trends-scraper is maintained by the same team behind the FortVPN Android app. If you find a bug or the endpoint moves, an issue with the raw payload is the fastest way to get it fixed.
Google Trends data and this scraper: common questions
What developers ask about the official API, the alternatives, and the numbers themselves.
Yes, but it is an alpha with access by application rather than a key you can generate. Google announced it in July 2025 and still describes it as a limited test, prioritising developers with a concrete use case. It serves the Explore-style dataset, so the Trending Now board used here is a separate product.
Add Google trending searches to your stack
One dependency-free function call, typed results, and errors you can branch on. Read the source before you install it — the whole request and parser are a few hundred lines.