Skip to content

Open source alternative to Semrush and Ahrefs

Keyword research: city and county search volume (EVE-125) (#676)

Carter Smith9961c15dbb2a
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.md
index 196f8684..2e361788 100644
--- a/.agents/PAPERCUTS.md
+++ b/.agents/PAPERCUTS.md
@@ -11,7 +11,7 @@ data, or sensitive paths.
## Open
- [ ] `2026-09-23T05:50:00Z` — `claude` — `pnpm install --frozen-lockfile` in `web/` rewrites the tracked `web/pnpm-workspace.yaml`, adding an `allowBuilds` block with `esbuild`/`workerd` set to the placeholder "set this to true or false". This leaves a dirty tree that is easy to commit by accident. Commit explicit `allowBuilds` values for those two packages.
-
+- [ ] `2026-09-23T04:52:00Z` — `claude` — `pnpm dev:agents` names the portless host after the git branch, and Linear branch names like `carter/eve-125-keyword-research-city-and-county-volume-not-just-country` make a 64-character DNS label (limit 63), so browsers show `chrome-error` for the `.localhost` URL. Workaround: open `http://127.0.0.1:<port>` from `.logs/dev-server.log`; fix: pass a truncated `--name` to portless in the script.
- [ ] `2026-09-22T02:21:38Z` — `codex` — The documented portless `.localhost` development URL produces a Google OAuth `invalid_request` because Google rejects that callback hostname. Document registering `http://localhost:<assigned-port>/api/gsc/oauth/callback` and starting the connection from that direct origin while the server remains managed by portless.
- [ ] `2026-09-18T10:06:56Z` — `codex` — Website browser tests flood Vite output with "Assets in public directory cannot be imported from JavaScript" for MDX library images. Adjust the MDX image handling to retain public image URLs instead of generating imports, so useful test failures remain visible.
- [ ] `2026-09-03T00:00:00Z` — `claude` — `pnpm ci:check` does not run `pnpm build`, so a route file that pulls `cloudflare:workers` into the client bundle passes every check and still breaks the build (hit on the dynamic-reports branch). Add a build step to `ci:check`, or document that `pnpm build` must be run separately before opening a PR.
diff --git a/.agents/skills/keyword-research/SKILL.md b/.agents/skills/keyword-research/SKILL.md
index ba553510..28d9db45 100644
--- a/.agents/skills/keyword-research/SKILL.md
+++ b/.agents/skills/keyword-research/SKILL.md
@@ -32,11 +32,11 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## OpenSEO MCP tools
-- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.
+- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research. For demand in one city, county, or region, call `search_serp_locations` and pass the returned `locationName` on the seed: volume, CPC, and competition become local; keyword ideas, KD, and intent stay national.
- `get_keyword_metrics`: hydrate up to 700 known keywords with volume, keyword difficulty (KD), search intent, CPC, and monthly trends in one call. Use it to score candidate or known terms — including the Search Console striking-distance queries from step 1.
- `get_ranked_keywords`: pull exact ranking keyword rows when a target domain or page is part of the research brief.
- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Pass `minPosition: 5, maxPosition: 20, minImpressions: 50` so the server filters the striking-distance rows for you (Google sorts by clicks and can't filter by position itself). Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
-- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous.
+- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous. Pass the same `locationName` for the SERP in one city, county, or region.
- `search_local_businesses`, `get_local_serp_results`, and `get_google_business_questions`: use for local SEO topics when a business/location radius matters.
- `list_saved_keywords`: avoid duplicating already-saved work or use existing tags as context.
- `save_keywords`: save selected keywords only after explicit user confirmation.
@@ -44,7 +44,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## Workflow
1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` with `minPosition: 5, maxPosition: 20, minImpressions: 50` (default lookback), and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
-2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
+2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Research local volume for that city or county with `research_keywords` and `locationName`. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
3. Call `research_keywords` for exploratory seeds. Use bulk calls when possible.
4. Use `get_keyword_metrics` to hydrate a fixed keyword list — or the striking-distance queries from step 1 — with volume, KD, and intent before prioritizing.
5. Use `get_ranked_keywords` when the user provides a domain/page and wants opportunities based on current rankings, near-misses, or competitor-owned terms.
diff --git a/plugins/openseo/skills/keyword-research/SKILL.md b/plugins/openseo/skills/keyword-research/SKILL.md
index ba553510..28d9db45 100644
--- a/plugins/openseo/skills/keyword-research/SKILL.md
+++ b/plugins/openseo/skills/keyword-research/SKILL.md
@@ -32,11 +32,11 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## OpenSEO MCP tools
-- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.
+- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research. For demand in one city, county, or region, call `search_serp_locations` and pass the returned `locationName` on the seed: volume, CPC, and competition become local; keyword ideas, KD, and intent stay national.
- `get_keyword_metrics`: hydrate up to 700 known keywords with volume, keyword difficulty (KD), search intent, CPC, and monthly trends in one call. Use it to score candidate or known terms — including the Search Console striking-distance queries from step 1.
- `get_ranked_keywords`: pull exact ranking keyword rows when a target domain or page is part of the research brief.
- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Pass `minPosition: 5, maxPosition: 20, minImpressions: 50` so the server filters the striking-distance rows for you (Google sorts by clicks and can't filter by position itself). Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
-- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous.
+- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous. Pass the same `locationName` for the SERP in one city, county, or region.
- `search_local_businesses`, `get_local_serp_results`, and `get_google_business_questions`: use for local SEO topics when a business/location radius matters.
- `list_saved_keywords`: avoid duplicating already-saved work or use existing tags as context.
- `save_keywords`: save selected keywords only after explicit user confirmation.
@@ -44,7 +44,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## Workflow
1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` with `minPosition: 5, maxPosition: 20, minImpressions: 50` (default lookback), and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
-2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
+2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Research local volume for that city or county with `research_keywords` and `locationName`. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
3. Call `research_keywords` for exploratory seeds. Use bulk calls when possible.
4. Use `get_keyword_metrics` to hydrate a fixed keyword list — or the striking-distance queries from step 1 — with volume, KD, and intent before prioritizing.
5. Use `get_ranked_keywords` when the user provides a domain/page and wants opportunities based on current rankings, near-misses, or competitor-owned terms.
diff --git a/specs/0004-keyword-data-source-routing.md b/specs/0004-keyword-data-source-routing.md
index f92c8125..8e113e12 100644
--- a/specs/0004-keyword-data-source-routing.md
+++ b/specs/0004-keyword-data-source-routing.md
@@ -114,3 +114,34 @@ USD × 1.28 markup × 1000):
clickstream-priced volumes never mix with standard ones.
- Reverting the clickstream default is a one-line change per fetcher in
`src/server/lib/dataforseo/labs.ts`; the opt-in plumbing stays either way.
+
+## Local volume (city, county, region)
+
+Keyword research can target one city, county, or region inside the selected
+country. Labs and clickstream serve countries only, so the keyword list,
+keyword difficulty, and intent stay national. One Google Ads `search_volume`
+call with the area's canonical `location_name` then replaces volume, trend,
+CPC, and competition for every row. The SERP panel fetches the organic results
+for the same area.
+
+- The area must be a row of the country's location registry, the same list
+ the rank tracking picker searches. The check runs before any paid call. The
+ registry has no postal codes, so ZIP targeting is not offered.
+- A keyword that Google Ads does not return gets empty metrics, never the
+ national numbers. Google Ads fails a whole task on one keyword with certain
+ symbols, an emoji, more than 80 characters, or more than 10 words, so those
+ keywords are not sent.
+- Local rows are not stored as keyword metrics, because stored metrics are
+ keyed by country. Saved keywords keep national metrics.
+
+Alternatives considered:
+
+- **Append the city to the keyword** ("plumber austin"). This is a different
+ query with its own, much smaller volume, not demand for the head term in
+ that city.
+- **Automatic fallback to the county or metro area when a small city has no
+ volume.** Google geotargets link a city to its state, not to its county or
+ metro area, so the fallback would need a separate city-to-county mapping.
+ The results instead suggest a larger area when no keyword has local volume.
+- **Coordinates or postal codes.** Coordinates resolve to country volume and
+ postal codes return no volume.
diff --git a/src/client/components/SerpLocationCombobox.tsx b/src/client/components/SerpLocationCombobox.tsx
index 1c4c9dcb..f8e08db1 100644
--- a/src/client/components/SerpLocationCombobox.tsx
+++ b/src/client/components/SerpLocationCombobox.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef, useState } from "react";
-import { Loader2, Search } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Loader2, MapPin } from "lucide-react";
import { searchSerpLocations } from "@/serverFunctions/serp-locations";
import { formatLocationLabel } from "@/shared/keyword-locations";
import type { SerpLocationResult } from "@/server/lib/dataforseo/serp-locations";
@@ -12,7 +12,7 @@ type Props = {
placeholder?: string;
};
-function useDebounce(value: string, delayMs: number): string {
+function useDebounce<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delayMs);
@@ -27,9 +27,8 @@ export function SerpLocationCombobox({
countryCode,
placeholder = "Search cities...",
}: Props) {
- const [inputValue, setInputValue] = useState(
- value ? formatLocationLabel(value) : "",
- );
+ const selectedLabel = value ? formatLocationLabel(value) : "";
+ const [inputValue, setInputValue] = useState(selectedLabel);
const [results, setResults] = useState<SerpLocationResult[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
@@ -37,54 +36,68 @@ export function SerpLocationCombobox({
const [activeIndex, setActiveIndex] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLUListElement>(null);
- // Selecting a result sets the input to its display label; that change must
- // not itself trigger a search for the label text.
- const skipNextFetchRef = useRef(false);
+ // The input shows the selection's label. Searching for that text again would
+ // reopen the list the selection just closed. A ref, so a new selection does
+ // not re-run the search for the text typed before it.
+ const selectedLabelRef = useRef(selectedLabel);
+ // Bumped by a pick or a blur, so a search still in flight cannot reopen the
+ // list the user just dismissed.
+ const searchGenerationRef = useRef(0);
- const debouncedQuery = useDebounce(inputValue, 350);
+ // Each keystroke makes a new query, so retyping a query the user dismissed
+ // before its debounce settled still starts a search.
+ const [editCount, setEditCount] = useState(0);
+ const query = useMemo(
+ () => ({ text: inputValue, editCount }),
+ [inputValue, editCount],
+ );
+ const debouncedQuery = useDebounce(query, 350);
- // Sync display when value prop changes externally (e.g. mode reset)
+ // Show the label of a value set from outside (a reset or a restored search).
useEffect(() => {
- if (!value) {
- setInputValue("");
+ selectedLabelRef.current = selectedLabel;
+ setInputValue(selectedLabel);
+ if (!selectedLabel) {
setResults([]);
setOpen(false);
}
- }, [value]);
+ }, [selectedLabel]);
// Fetch results when debounced query changes
useEffect(() => {
- const trimmed = debouncedQuery.trim();
+ const trimmed = debouncedQuery.text.trim();
if (!trimmed) {
setResults([]);
setOpen(false);
setIsLoading(false);
return;
}
- if (skipNextFetchRef.current) {
- skipNextFetchRef.current = false;
+ if (trimmed === selectedLabelRef.current) {
// Any fetch this change superseded was cancelled before its own
// finally could clear the spinner, so clear it here.
setIsLoading(false);
return;
}
let cancelled = false;
+ const generation = searchGenerationRef.current;
+ const isStale = () =>
+ cancelled || generation !== searchGenerationRef.current;
setIsLoading(true);
setIsError(false);
searchSerpLocations({ data: { query: trimmed, countryCode } })
.then((data) => {
- if (cancelled) return;
+ if (isStale()) return;
setResults(data);
setOpen(true);
setActiveIndex(0);
})
.catch(() => {
- if (cancelled) return;
+ if (isStale()) return;
setIsError(true);
setOpen(true);
})
.finally(() => {
- if (!cancelled) setIsLoading(false);
+ if (!isStale()) setIsLoading(false);
});
return () => {
cancelled = true;
@@ -114,9 +127,14 @@ export function SerpLocationCombobox({
});
}, [activeIndex, open]);
+ const dismissPendingSearch = () => {
+ searchGenerationRef.current += 1;
+ setIsLoading(false);
+ };
+
const select = (loc: SerpLocationResult) => {
+ dismissPendingSearch();
onChange(loc.locationName);
- skipNextFetchRef.current = true;
setInputValue(loc.displayLabel);
setResults([]);
setOpen(false);
@@ -125,13 +143,22 @@ export function SerpLocationCombobox({
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const v = e.target.value;
setInputValue(v);
+ setEditCount((count) => count + 1);
if (!v.trim()) {
onChange(undefined);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
- if (!open) return;
+ if (!open) {
+ // Text that is not a picked location must not submit the form with
+ // the previous selection: wait for the list, then pick a result.
+ const typed = inputValue.trim();
+ if (e.key === "Enter" && typed && typed !== selectedLabelRef.current) {
+ e.preventDefault();
+ }
+ return;
+ }
switch (e.key) {
case "ArrowDown":
e.preventDefault();
@@ -155,12 +182,26 @@ export function SerpLocationCombobox({
};
return (
- <div ref={containerRef} className="relative w-full">
+ <div
+ ref={containerRef}
+ className="relative w-full"
+ onBlur={(e) => {
+ if (containerRef.current?.contains(e.relatedTarget)) return;
+ // Leaving without picking a result shows the selection again, so the
+ // field never names a place the form will not use.
+ dismissPendingSearch();
+ setInputValue(selectedLabelRef.current);
+ // The matches were for the abandoned text; focusing again must not
+ // offer them under the restored label.
+ setResults([]);
+ setOpen(false);
+ }}
+ >
<label className="flex items-center gap-2 input input-bordered w-full pr-3">
{isLoading ? (
<Loader2 className="size-4 shrink-0 text-base-content/50 animate-spin" />
) : (
- <Search className="size-4 shrink-0 text-base-content/50" />
+ <MapPin className="size-4 shrink-0 text-base-content/50" />
)}
<input
type="text"
@@ -177,14 +218,18 @@ export function SerpLocationCombobox({
</label>
{open && (
- <div className="absolute z-30 mt-1 w-full rounded-box border border-base-300 bg-base-100 shadow-lg p-1">
+ <div
+ className="absolute z-30 mt-1 w-full rounded-box border border-base-300 bg-base-100 shadow-lg p-1"
+ // Keep focus in the input, so picking a result is not a blur.
+ onMouseDown={(e) => e.preventDefault()}
+ >
{isError ? (
<p className="px-3 py-2 text-sm text-error">
Unable to load locations
</p>
) : results.length === 0 ? (
<p className="px-3 py-2 text-sm text-base-content/50">
- No locations found for "{debouncedQuery.trim()}"
+ No locations found for "{debouncedQuery.text.trim()}"
</p>
) : (
<ul
diff --git a/src/client/components/usePrewarmSerpLocations.ts b/src/client/components/usePrewarmSerpLocations.ts
new file mode 100644
index 00000000..1fb1e507
--- /dev/null
+++ b/src/client/components/usePrewarmSerpLocations.ts
@@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { prewarmSerpLocations } from "@/serverFunctions/serp-locations";
+
+/**
+ * Warm the server-side location cache before the first keystroke, so the
+ * country list is hot when the user searches. Best-effort: a failed warm just
+ * means the first search is slower, so no retries, and staleTime keeps one
+ * warm per country per session.
+ */
+export function usePrewarmSerpLocations(countryCode: string, enabled: boolean) {
+ useQuery({
+ queryKey: ["serp-locations-prewarm", countryCode],
+ queryFn: () => prewarmSerpLocations({ data: { countryCode } }),
+ enabled,
+ staleTime: Infinity,
+ retry: false,
+ });
+}
diff --git a/src/client/features/keywords/hooks/useKeywordControlsForm.ts b/src/client/features/keywords/hooks/useKeywordControlsForm.ts
index 024fed57..3b3f0cf5 100644
--- a/src/client/features/keywords/hooks/useKeywordControlsForm.ts
+++ b/src/client/features/keywords/hooks/useKeywordControlsForm.ts
@@ -14,6 +14,7 @@ import { parseKeywordInput } from "@/client/features/keywords/state/keywordContr
type UseKeywordControlsFormInput = {
keywordInput: string;
locationCode: number;
+ locationName: string | undefined;
resultLimit: ResultLimit;
keywordMode: KeywordMode;
clickstream: boolean;
@@ -22,6 +23,7 @@ type UseKeywordControlsFormInput = {
export type KeywordControlsValues = {
keyword: string;
locationCode: number;
+ locationName: string | undefined;
resultLimit: ResultLimit;
mode: KeywordMode;
clickstream: boolean;
@@ -64,6 +66,7 @@ export function useKeywordControlsForm(
defaultValues: {
keyword: input.keywordInput,
locationCode: input.locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.keywordMode,
clickstream: input.clickstream,
@@ -87,6 +90,7 @@ export function useKeywordControlsForm(
form.reset({
keyword: input.keywordInput,
locationCode: input.locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.keywordMode,
clickstream: input.clickstream,
@@ -96,6 +100,7 @@ export function useKeywordControlsForm(
input.keywordInput,
input.keywordMode,
input.locationCode,
+ input.locationName,
input.resultLimit,
input.clickstream,
]);
diff --git a/src/client/features/keywords/hooks/useKeywordResearchData.test.ts b/src/client/features/keywords/hooks/useKeywordResearchData.test.ts
index 3b761696..bcf6c322 100644
--- a/src/client/features/keywords/hooks/useKeywordResearchData.test.ts
+++ b/src/client/features/keywords/hooks/useKeywordResearchData.test.ts
@@ -13,6 +13,7 @@ const baseInput = {
projectId: "project_1",
keywordInput: "technical seo",
locationCode: 2704,
+ locationName: undefined,
resultLimit: 150 as const,
mode: "auto" as const,
clickstream: false,
@@ -35,6 +36,19 @@ describe("buildKeywordResearchRequest", () => {
);
});
+ it("never serves a national result for a local search", () => {
+ const national = buildKeywordResearchRequest(baseInput);
+ const local = buildKeywordResearchRequest({
+ ...baseInput,
+ locationName: "Hanoi,Hanoi,Vietnam",
+ });
+
+ expect(local).toMatchObject({ locationName: "Hanoi,Hanoi,Vietnam" });
+ expect(buildKeywordResearchQueryKey(local)).not.toEqual(
+ buildKeywordResearchQueryKey(national),
+ );
+ });
+
it("leaves the location undefined for the server to resolve", () => {
const request = buildKeywordResearchRequest({
...baseInput,
diff --git a/src/client/features/keywords/hooks/useKeywordResearchData.ts b/src/client/features/keywords/hooks/useKeywordResearchData.ts
index 7bd35606..6ec7b146 100644
--- a/src/client/features/keywords/hooks/useKeywordResearchData.ts
+++ b/src/client/features/keywords/hooks/useKeywordResearchData.ts
@@ -3,6 +3,7 @@ import { useQuery } from "@tanstack/react-query";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import { LOCATIONS } from "@/client/features/keywords/utils";
+import { formatLocationLabel } from "@/shared/keyword-locations";
import { parseKeywordInput } from "@/client/features/keywords/state/keywordControllerActions";
import { researchKeywords } from "@/serverFunctions/keywords";
import type {
@@ -13,13 +14,15 @@ import type {
type AddSearchFn = (
keyword: string,
locationCode: number,
- locationName: string,
+ locationLabel: string,
+ localLocationName: string | undefined,
) => void;
type KeywordResearchRequestInput = {
projectId: string;
keywordInput: string;
locationCode: number | undefined;
+ locationName: string | undefined;
resultLimit: ResultLimit;
mode: KeywordMode;
clickstream: boolean;
@@ -35,6 +38,7 @@ type KeywordResearchRequest = {
keywords: string[];
seedKeyword: string;
locationCode: number | undefined;
+ locationName: string | undefined;
resultLimit: ResultLimit;
mode: KeywordMode;
clickstream: boolean;
@@ -55,6 +59,7 @@ export function buildKeywordResearchRequest(
keywords,
seedKeyword,
locationCode: input.locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.mode,
clickstream: input.clickstream,
@@ -71,6 +76,7 @@ export function buildKeywordResearchQueryKey(
request.projectId,
request.keywords,
request.locationCode,
+ request.locationName,
request.resultLimit,
request.mode,
request.clickstream,
@@ -85,6 +91,7 @@ export function keywordResearchQueryFn(request: KeywordResearchRequest) {
projectId: request.projectId,
keywords: request.keywords,
locationCode: request.locationCode,
+ locationName: request.locationName,
resultLimit: request.resultLimit,
mode: request.mode,
clickstream: request.clickstream,
@@ -103,6 +110,7 @@ export function useKeywordResearchData(
displayedLocationCode,
keywordInput,
locationCode,
+ locationName,
mode,
projectId,
resultLimit,
@@ -112,6 +120,7 @@ export function useKeywordResearchData(
buildKeywordResearchRequest({
keywordInput,
locationCode,
+ locationName,
mode,
projectId,
resultLimit,
@@ -123,6 +132,7 @@ export function useKeywordResearchData(
groupKeywords,
keywordInput,
locationCode,
+ locationName,
mode,
projectId,
resultLimit,
@@ -161,13 +171,17 @@ export function useKeywordResearchData(
location_code: displayedLocationCode,
search_mode: request.mode,
clickstream: request.clickstream,
+ local: request.locationName !== undefined,
result_count: researchQuery.data.rows.length,
});
addSearch(
request.seedKeyword,
displayedLocationCode,
- LOCATIONS[displayedLocationCode] || "Unknown",
+ request.locationName
+ ? formatLocationLabel(request.locationName)
+ : LOCATIONS[displayedLocationCode] || "Unknown",
+ request.locationName,
);
}, [
addSearch,
diff --git a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts
index de11c1af..ccad5655 100644
--- a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts
+++ b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts
@@ -16,6 +16,7 @@ const SERP_DEEP_DEPTH = 100;
export function useKeywordSerpAnalysis(
projectId: string,
locationCode: number | undefined,
+ locationName: string | undefined,
) {
const [serpKeyword, setSerpKeywordState] = useState<string | null>(null);
const [serpPage, setSerpPageState] = useState(0);
@@ -25,7 +26,13 @@ export function useKeywordSerpAnalysis(
// Everything but the depth identifies the snapshot; the depth decides how
// deep it goes.
- const snapshotKey = ["serpAnalysis", projectId, serpKeyword, locationCode];
+ const snapshotKey = [
+ "serpAnalysis",
+ projectId,
+ serpKeyword,
+ locationCode,
+ locationName,
+ ];
const serpQuery = useQuery({
queryKey: [...snapshotKey, requestedDepth],
@@ -35,6 +42,7 @@ export function useKeywordSerpAnalysis(
projectId,
keyword: serpKeyword!,
locationCode,
+ locationName,
depth: requestedDepth,
},
}),
diff --git a/src/client/features/keywords/keywordSearchParams.ts b/src/client/features/keywords/keywordSearchParams.ts
index 95e7aca0..9c31d021 100644
--- a/src/client/features/keywords/keywordSearchParams.ts
+++ b/src/client/features/keywords/keywordSearchParams.ts
@@ -7,6 +7,7 @@ import type {
type KeywordSearchParams = {
q?: string;
loc?: number;
+ locName?: string;
kLimit?: ResultLimit;
mode?: KeywordMode;
cs?: boolean;
@@ -31,6 +32,7 @@ export function normalizeLegacyKeywordSearch(search: KeywordSearchParams): {
...search,
q: search.q === "" ? undefined : search.q,
loc: search.loc,
+ locName: search.locName === "" ? undefined : search.locName,
kLimit: search.kLimit === 150 ? undefined : search.kLimit,
mode: search.mode === "auto" ? undefined : search.mode,
cs: search.cs === true ? true : undefined,
@@ -50,6 +52,7 @@ export function normalizeLegacyKeywordSearch(search: KeywordSearchParams): {
const keys: Array<keyof KeywordSearchParams> = [
"q",
"loc",
+ "locName",
"kLimit",
"mode",
"cs",
diff --git a/src/client/features/keywords/page/KeywordAreaField.tsx b/src/client/features/keywords/page/KeywordAreaField.tsx
new file mode 100644
index 00000000..db6db14d
--- /dev/null
+++ b/src/client/features/keywords/page/KeywordAreaField.tsx
@@ -0,0 +1,53 @@
+import { useState } from "react";
+import { SerpLocationCombobox } from "@/client/components/SerpLocationCombobox";
+import { usePrewarmSerpLocations } from "@/client/components/usePrewarmSerpLocations";
+import { isHostedClientAuthMode } from "@/lib/auth-mode";
+import { LOCAL_VOLUME_COST_USD, applyBillingMarkupUsd } from "@/shared/billing";
+import { getIsoCountryCode } from "@/shared/keyword-locations";
+
+type Props = {
+ locationCode: number;
+ value: string | undefined;
+ onChange: (locationName: string | undefined) => void;
+};
+
+/**
+ * Optional city, county, or region inside the selected country. Empty means
+ * national volume. The location list is warmed on first focus, so page views
+ * that never use the field cost nothing.
+ */
+export function KeywordAreaField({ locationCode, value, onChange }: Props) {
+ const [focused, setFocused] = useState(false);
+ const countryCode = getIsoCountryCode(locationCode);
+ usePrewarmSerpLocations(countryCode, focused);
+
+ return (
+ <div
+ className="col-span-2 w-full lg:w-60 lg:shrink-0"
+ onFocus={() => setFocused(true)}
+ title="Get search volume for one city, county, or region. Leave empty for the whole country."
+ >
+ <SerpLocationCombobox
+ value={value}
+ onChange={onChange}
+ countryCode={countryCode}
+ placeholder="City or county (optional)"
+ />
+ </div>
+ );
+}
+
+/**
+ * The extra Google Ads lookup a local search makes. Hosted users pay the
+ * marked-up price; self-hosted deployments pay DataForSEO directly.
+ */
+export function LocalVolumeCostNote() {
+ const costUsd = isHostedClientAuthMode()
+ ? applyBillingMarkupUsd(LOCAL_VOLUME_COST_USD)
+ : LOCAL_VOLUME_COST_USD;
+ return (
+ <span className="text-xs text-base-content/60">
+ Local volume adds ~${costUsd.toFixed(2)} per search.
+ </span>
+ );
+}
diff --git a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
index 3dc98e7e..4af0581b 100644
--- a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
@@ -11,8 +11,8 @@ import {
import { sortBy } from "remeda";
import {
downloadKeywordResearchCsv,
- KEYWORD_RESEARCH_HEADERS,
keywordResearchExportRow,
+ keywordResearchHeaders,
} from "@/client/features/keywords/state/keywordControllerActions";
import { exportTableToSheets } from "@/client/lib/exportToSheets";
import { captureClientEvent } from "@/client/lib/posthog";
@@ -140,22 +140,23 @@ function DesktopTableCard({ controller }: Props) {
const selectedExportRows = rows
.filter((row) => selectedRows.has(row.keyword))
.map(keywordResearchExportRow);
+ const exportHeaders = keywordResearchHeaders(controller.locationName);
const handleExportToSheets = () => {
void exportTableToSheets({
- headers: KEYWORD_RESEARCH_HEADERS,
+ headers: exportHeaders,
rows: sheetsExportRows,
feature: "keyword_research",
});
};
const handleExportSelectionToSheets = () => {
void exportTableToSheets({
- headers: KEYWORD_RESEARCH_HEADERS,
+ headers: exportHeaders,
rows: selectedExportRows,
feature: "keyword_research",
});
};
const handleExportSelectionCsv = () => {
- downloadKeywordResearchCsv(selectedExportRows);
+ downloadKeywordResearchCsv(selectedExportRows, exportHeaders);
captureClientEvent("data:export", {
source_feature: "keyword_research",
result_count: selectedExportRows.length,
diff --git a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx b/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
index b0acc415..9fb3d024 100644
--- a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
+++ b/src/client/features/keywords/page/KeywordResearchEmptyState.tsx
@@ -89,6 +89,7 @@ function SearchHistoryState({
search={{
q: item.keyword,
loc: item.locationCode,
+ locName: item.localLocationName,
grp: controller.preferredGroupKeywords ? true : undefined,
}}
replace
diff --git a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx b/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
index ac6cfda5..eb83fa6b 100644
--- a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
@@ -9,8 +9,8 @@ import {
} from "lucide-react";
import {
downloadKeywordResearchCsv,
- KEYWORD_RESEARCH_HEADERS,
keywordResearchExportRow,
+ keywordResearchHeaders,
} from "@/client/features/keywords/state/keywordControllerActions";
import { exportTableToSheets } from "@/client/lib/exportToSheets";
import { captureClientEvent } from "@/client/lib/posthog";
@@ -115,22 +115,23 @@ function MobileKeywordResults({ controller }: Props) {
const selectedExportRows = rows
.filter((row) => selectedRows.has(row.keyword))
.map(keywordResearchExportRow);
+ const exportHeaders = keywordResearchHeaders(controller.locationName);
const handleExportToSheets = () => {
void exportTableToSheets({
- headers: KEYWORD_RESEARCH_HEADERS,
+ headers: exportHeaders,
rows: sheetsExportRows,
feature: "keyword_research",
});
};
const handleExportSelectionToSheets = () => {
void exportTableToSheets({
- headers: KEYWORD_RESEARCH_HEADERS,
+ headers: exportHeaders,
rows: selectedExportRows,
feature: "keyword_research",
});
};
const handleExportSelectionCsv = () => {
- downloadKeywordResearchCsv(selectedExportRows);
+ downloadKeywordResearchCsv(selectedExportRows, exportHeaders);
captureClientEvent("data:export", {
source_feature: "keyword_research",
result_count: selectedExportRows.length,
diff --git a/src/client/features/keywords/page/KeywordResearchPage.tsx b/src/client/features/keywords/page/KeywordResearchPage.tsx
index 0f08c0e9..15366bcb 100644
--- a/src/client/features/keywords/page/KeywordResearchPage.tsx
+++ b/src/client/features/keywords/page/KeywordResearchPage.tsx
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from "react";
import { AlertCircle, ArrowLeft } from "lucide-react";
import { getErrorCode } from "@/client/lib/error-messages";
import { BILLING_ROUTE } from "@/shared/billing";
+import { formatLocationLabel } from "@/shared/keyword-locations";
import { useKeywordResearchController } from "@/client/features/keywords/state/useKeywordResearchController";
import type {
KeywordResearchControllerInput,
@@ -54,6 +55,7 @@ export function KeywordResearchPage(input: Props) {
setSearchParams({
q: undefined,
loc: undefined,
+ locName: undefined,
kLimit: undefined,
mode: undefined,
cs: undefined,
@@ -65,6 +67,7 @@ export function KeywordResearchPage(input: Props) {
setSearchParams({
q: tabInput.keyword,
loc: tabInput.locationCode,
+ locName: tabInput.locationName,
kLimit: tabInput.resultLimit === 150 ? undefined : tabInput.resultLimit,
mode: tabInput.mode === "auto" ? undefined : tabInput.mode,
cs: tabInput.clickstream ? true : undefined,
@@ -82,6 +85,7 @@ export function KeywordResearchPage(input: Props) {
type: "keyword",
keyword,
locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.keywordMode,
clickstream: input.clickstream,
@@ -92,16 +96,19 @@ export function KeywordResearchPage(input: Props) {
input.groupKeywords,
input.keywordInput,
input.keywordMode,
+ input.locationName,
locationCode,
input.resultLimit,
]);
const searchTabs = useSearchTabNavigation({
storageKey: `keyword:${projectId}`,
urlInput,
- getLabel: useCallback(
- (tabInput) => (tabInput.type === "keyword" ? tabInput.keyword : ""),
- [],
- ),
+ getLabel: useCallback((tabInput) => {
+ if (tabInput.type !== "keyword") return "";
+ return tabInput.locationName
+ ? `${tabInput.keyword} · ${formatLocationLabel(tabInput.locationName, 1)}`
+ : tabInput.keyword;
+ }, []),
navigateToInput: useCallback(
(tabInput) => {
navigateToKeywordInput(tabInput?.type === "keyword" ? tabInput : null);
@@ -133,6 +140,7 @@ export function KeywordResearchPage(input: Props) {
type: "keyword",
keyword,
locationCode: value.locationCode,
+ locationName: value.locationName,
resultLimit: value.resultLimit,
mode: value.mode,
clickstream: value.clickstream,
@@ -159,6 +167,7 @@ export function KeywordResearchPage(input: Props) {
locationCode: activeTab.input.locationCode,
displayedLocationCode:
activeTab.input.locationCode ?? displayedLocationCode,
+ locationName: activeTab.input.locationName,
setPreferredLocationCode,
resultLimit: activeTab.input.resultLimit,
keywordMode: activeTab.input.mode,
@@ -238,8 +247,7 @@ function KeywordResearchContent({
}
if (controller.researchError) {
- const isCreditsError =
- getErrorCode(controller.researchMutationError) === "INSUFFICIENT_CREDITS";
+ const errorCode = getErrorCode(controller.researchMutationError);
return (
<div className="flex-1 flex items-center justify-center pt-1">
@@ -248,11 +256,11 @@ function KeywordResearchContent({
<AlertCircle className="mt-0.5 size-4 shrink-0" />
<p className="text-sm">{controller.researchError}</p>
</div>
- {isCreditsError ? (
+ {errorCode === "INSUFFICIENT_CREDITS" ? (
<Link to={BILLING_ROUTE} className="btn btn-sm">
Go to Billing
</Link>
- ) : (
+ ) : errorCode === "UNKNOWN_LOCATION" ? null : (
<button className="btn btn-sm" onClick={controller.retrySearch}>
Try again
</button>
@@ -291,6 +299,12 @@ function KeywordSaveDialog({
<p className="text-base-content/70 text-sm">
These keywords will be saved to your current project.
</p>
+ {controller.locationName ? (
+ <p className="mt-2 text-base-content/70 text-sm">
+ Saved keywords show national metrics. The local volume for{" "}
+ {formatLocationLabel(controller.locationName)} is not saved.
+ </p>
+ ) : null}
</div>
<div className="modal-action">
<button
diff --git a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
index 84a1d50a..b714cf4c 100644
--- a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
+++ b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
@@ -1,15 +1,10 @@
import { Info, Search } from "lucide-react";
import { getFieldError } from "@/client/lib/forms";
-import {
- isResultLimit,
- normalizeKeywordMode,
-} from "@/client/features/keywords/keywordSearchParams";
-import {
- MAX_KEYWORDS_PER_SUBMIT,
- RESULT_LIMITS,
-} from "@/client/features/keywords/keywordResearchTypes";
+import { MAX_KEYWORDS_PER_SUBMIT } from "@/client/features/keywords/keywordResearchTypes";
import { isLabsLocationCode } from "@/client/features/keywords/locations";
import { LocationSelect } from "@/client/components/LocationSelect";
+import { KeywordAreaField, LocalVolumeCostNote } from "./KeywordAreaField";
+import { KeywordSearchOptions } from "./KeywordSearchOptions";
import type { KeywordResearchControllerState } from "./types";
type Props = {
@@ -38,14 +33,18 @@ export function KeywordResearchSearchBar({ controller }: Props) {
const rows = getTextareaRows(field.state.value);
return (
+ // Same input styling as the location field beside it. Extra
+ // lines grow the field.
<label
- className={`flex w-full lg:flex-1 lg:min-w-0 lg:max-w-md items-start gap-2 rounded-lg border bg-base-100 px-4 py-3 transition-colors focus-within:border-primary ${
- keywordError ? "border-error" : "border-base-300"
- }`}
+ className={`input input-bordered flex w-full lg:flex-1 lg:min-w-0 lg:max-w-md gap-2 pr-3 ${
+ rows > 1 ? "h-auto items-start py-2" : "items-center"
+ } ${keywordError ? "input-error" : ""}`}
>
- <Search className="mt-0.5 size-4 shrink-0 text-base-content/60" />
+ <Search
+ className={`size-4 shrink-0 text-base-content/50 ${rows > 1 ? "mt-1" : ""}`}
+ />
<textarea
- className="grow min-w-0 resize-none bg-transparent text-sm leading-6 outline-none placeholder:text-base-content/40"
+ className="grow min-w-0 resize-none bg-transparent leading-6 outline-none placeholder:text-base-content/40"
rows={rows}
placeholder="Enter a keyword"
value={field.state.value}
@@ -70,47 +69,33 @@ export function KeywordResearchSearchBar({ controller }: Props) {
{(field) => (
<LocationSelect
value={field.state.value}
- onChange={(code) => field.handleChange(code)}
- className="w-full lg:w-44 lg:shrink-0"
+ onChange={(code) => {
+ field.handleChange(code);
+ // An area belongs to one country.
+ controlsForm.setFieldValue("locationName", undefined);
+ }}
+ className="col-span-2 w-full lg:w-44 lg:shrink-0"
/>
)}
</controlsForm.Field>
- <controlsForm.Field name="resultLimit">
- {(field) => (
- <select
- className="select select-bordered w-full lg:w-auto lg:shrink-0"
- value={field.state.value}
- onChange={(event) => {
- const next = Number(event.target.value);
- field.handleChange(isResultLimit(next) ? next : 150);
- }}
- >
- {RESULT_LIMITS.map((limit) => (
- <option key={limit} value={limit}>
- {limit} results
- </option>
- ))}
- </select>
+ <controlsForm.Subscribe
+ selector={(state) => state.values.locationCode}
+ >
+ {(locationCode) => (
+ <controlsForm.Field name="locationName">
+ {(field) => (
+ <KeywordAreaField
+ locationCode={locationCode}
+ value={field.state.value}
+ onChange={(name) => field.handleChange(name)}
+ />
+ )}
+ </controlsForm.Field>
)}
- </controlsForm.Field>
+ </controlsForm.Subscribe>
- <controlsForm.Field name="mode">
- {(field) => (
- <select
- className="select select-bordered w-full lg:w-auto lg:shrink-0"
- value={field.state.value}
- onChange={(event) =>
- field.handleChange(normalizeKeywordMode(event.target.value))
- }
- >
- <option value="auto">Auto</option>
- <option value="suggestions">Phrase match</option>
- <option value="ideas">Category ideas</option>
- <option value="related">People also search for</option>
- </select>
- )}
- </controlsForm.Field>
+ <KeywordSearchOptions controller={controller} />
<button
type="submit"
@@ -129,50 +114,14 @@ export function KeywordResearchSearchBar({ controller }: Props) {
) : null;
}}
</controlsForm.Field>
- <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
- <label className="label cursor-pointer justify-start gap-2 p-0">
- <input
- type="checkbox"
- role="switch"
- className="toggle toggle-sm toggle-primary"
- checked={controller.preferredGroupKeywords}
- onChange={(event) =>
- controller.setPreferredGroupKeywords(event.target.checked)
- }
- />
- <span className="text-sm font-medium text-base-content/80">
- Group keywords
- </span>
- </label>
- <controlsForm.Field name="locationCode">
- {(locationField) =>
- isLabsLocationCode(locationField.state.value) ? (
- <controlsForm.Field name="clickstream">
- {(field) => (
- <div className="flex items-center gap-2">
- <label className="label cursor-pointer justify-start gap-2 p-0">
- <input
- type="checkbox"
- className="toggle toggle-sm toggle-primary"
- checked={field.state.value}
- onChange={(event) =>
- field.handleChange(event.target.checked)
- }
- />
- <span className="text-sm font-medium text-base-content/80">
- Clickstream-refined volumes
- </span>
- </label>
- <div
- className="tooltip tooltip-right"
- data-tip="Google reports one combined search volume for similar keywords (e.g. 'seo tool' and 'seo tools'). Turn this on to estimate each keyword's own volume. Costs 2x the credits."
- >
- <Info className="size-3.5 text-base-content/50" />
- </div>
- </div>
- )}
- </controlsForm.Field>
- ) : (
+ <controlsForm.Subscribe
+ selector={(state) =>
+ [state.values.locationCode, state.values.locationName] as const
+ }
+ >
+ {([locationCode, locationName]) => (
+ <>
+ {isLabsLocationCode(locationCode) ? null : (
<div
className="flex items-start gap-2 rounded-lg border border-info/30 bg-info/10 px-3 py-2 text-sm text-base-content/80"
role="status"
@@ -184,10 +133,11 @@ export function KeywordResearchSearchBar({ controller }: Props) {
intent are not.
</span>
</div>
- )
- }
- </controlsForm.Field>
- </div>
+ )}
+ {locationName ? <LocalVolumeCostNote /> : null}
+ </>
+ )}
+ </controlsForm.Subscribe>
</div>
</div>
);
diff --git a/src/client/features/keywords/page/KeywordSearchOptions.tsx b/src/client/features/keywords/page/KeywordSearchOptions.tsx
new file mode 100644
index 00000000..fbd6b7ea
--- /dev/null
+++ b/src/client/features/keywords/page/KeywordSearchOptions.tsx
@@ -0,0 +1,208 @@
+import { useState } from "react";
+import { SlidersHorizontal } from "lucide-react";
+import { Modal } from "@/client/components/Modal";
+import {
+ isResultLimit,
+ normalizeKeywordMode,
+} from "@/client/features/keywords/keywordSearchParams";
+import { RESULT_LIMITS } from "@/client/features/keywords/keywordResearchTypes";
+import { isLabsLocationCode } from "@/client/features/keywords/locations";
+import type { KeywordResearchControllerState } from "./types";
+
+type Props = {
+ controller: KeywordResearchControllerState;
+};
+
+const GOOGLE_ADS_ONLY_NOTE =
+ "Not available for countries served from Google Ads data.";
+
+/** The search settings most people leave at their defaults. */
+export function KeywordSearchOptions({ controller }: Props) {
+ const {
+ controlsForm,
+ preferredGroupKeywords: groupKeywords,
+ setPreferredGroupKeywords: setGroupKeywords,
+ } = controller;
+ const [open, setOpen] = useState(false);
+
+ return (
+ <controlsForm.Subscribe selector={(state) => state.values}>
+ {(values) => {
+ // Google-Ads-only countries ignore source, clickstream, and grouping.
+ const labs = isLabsLocationCode(values.locationCode);
+ const local = Boolean(values.locationName);
+
+ return (
+ <>
+ <button
+ type="button"
+ className="btn w-full gap-2 border-base-300 bg-base-100 font-normal lg:w-auto lg:shrink-0"
+ aria-haspopup="dialog"
+ onClick={() => setOpen(true)}
+ >
+ <SlidersHorizontal className="size-4" />
+ Options
+ </button>
+
+ {open ? (
+ <Modal
+ maxWidth="max-w-md"
+ onClose={() => setOpen(false)}
+ labelledBy="keyword-search-options-title"
+ >
+ <h3
+ id="keyword-search-options-title"
+ className="text-lg font-semibold"
+ >
+ Search options
+ </h3>
+
+ <controlsForm.Field name="resultLimit">
+ {(field) => (
+ <OptionRow label="Results">
+ <select
+ className="select select-bordered w-full"
+ value={field.state.value}
+ onChange={(event) => {
+ const next = Number(event.target.value);
+ field.handleChange(isResultLimit(next) ? next : 150);
+ }}
+ >
+ {RESULT_LIMITS.map((limit) => (
+ <option key={limit} value={limit}>
+ {limit} results
+ </option>
+ ))}
+ </select>
+ </OptionRow>
+ )}
+ </controlsForm.Field>
+
+ <controlsForm.Field name="mode">
+ {(field) => (
+ <OptionRow
+ label="Keyword source"
+ help={labs ? undefined : GOOGLE_ADS_ONLY_NOTE}
+ >
+ <select
+ className="select select-bordered w-full"
+ value={field.state.value}
+ disabled={!labs}
+ onChange={(event) =>
+ field.handleChange(
+ normalizeKeywordMode(event.target.value),
+ )
+ }
+ >
+ <option value="auto">Auto</option>
+ <option value="suggestions">Phrase match</option>
+ <option value="ideas">Category ideas</option>
+ <option value="related">People also search for</option>
+ </select>
+ </OptionRow>
+ )}
+ </controlsForm.Field>
+
+ <controlsForm.Field name="clickstream">
+ {(field) => (
+ <ToggleRow
+ label="Clickstream-refined volumes"
+ help={
+ !labs
+ ? GOOGLE_ADS_ONLY_NOTE
+ : local
+ ? "Not available for local results. Clickstream data covers whole countries only."
+ : "Google reports one combined volume for similar keywords. This estimates each keyword's own volume. Costs 2x the credits."
+ }
+ // The saved choice returns when the option applies again.
+ checked={labs && !local && field.state.value}
+ disabled={!labs || local}
+ onChange={(checked) => field.handleChange(checked)}
+ />
+ )}
+ </controlsForm.Field>
+
+ <ToggleRow
+ label="Group keywords"
+ help={labs ? undefined : GOOGLE_ADS_ONLY_NOTE}
+ checked={labs && groupKeywords}
+ disabled={!labs}
+ onChange={setGroupKeywords}
+ />
+
+ <div className="flex justify-end pt-2">
+ <button
+ type="button"
+ className="btn btn-primary btn-sm"
+ onClick={() => setOpen(false)}
+ >
+ Done
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+ </>
+ );
+ }}
+ </controlsForm.Subscribe>
+ );
+}
+
+function OptionRow({
+ label,
+ help,
+ children,
+}: {
+ label: string;
+ help?: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <label className="flex flex-col gap-1.5">
+ <span className="text-sm font-medium">{label}</span>
+ {children}
+ {help ? (
+ <span className="text-xs text-base-content/60">{help}</span>
+ ) : null}
+ </label>
+ );
+}
+
+function ToggleRow({
+ label,
+ help,
+ checked,
+ disabled,
+ onChange,
+}: {
+ label: string;
+ help?: string;
+ checked: boolean;
+ disabled: boolean;
+ onChange: (checked: boolean) => void;
+}) {
+ return (
+ <label
+ className={`flex items-start justify-between gap-4 ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}
+ >
+ <span className="flex flex-col gap-0.5">
+ <span
+ className={`text-sm font-medium ${disabled ? "text-base-content/40" : ""}`}
+ >
+ {label}
+ </span>
+ {help ? (
+ <span className="text-xs text-base-content/60">{help}</span>
+ ) : null}
+ </span>
+ <input
+ type="checkbox"
+ role="switch"
+ className="toggle toggle-sm toggle-primary mt-0.5 shrink-0"
+ checked={checked}
+ disabled={disabled}
+ onChange={(event) => onChange(event.target.checked)}
+ />
+ </label>
+ );
+}
diff --git a/src/client/features/keywords/state/keywordControllerActions.ts b/src/client/features/keywords/state/keywordControllerActions.ts
index 069fef2f..b3c146d0 100644
--- a/src/client/features/keywords/state/keywordControllerActions.ts
+++ b/src/client/features/keywords/state/keywordControllerActions.ts
@@ -11,15 +11,22 @@ import type {
} from "@/client/features/keywords/keywordResearchTypes";
import type { KeywordResearchControllerInput } from "./useKeywordResearchController";
import type { KeywordResearchDisplayRow } from "@/client/features/keywords/groupSharedVolumeRows";
+import { formatLocationLabel } from "@/shared/keyword-locations";
-export const KEYWORD_RESEARCH_HEADERS = [
- "Keyword",
- "Volume",
- "CPC",
- "Competition",
- "Score",
- "Intent",
-];
+/** Local exports name the area the volume, CPC, and competition cover. */
+export function keywordResearchHeaders(locationName?: string) {
+ const scope = locationName ? ` (${formatLocationLabel(locationName)})` : "";
+ return [
+ "Keyword",
+ `Volume${scope}`,
+ `CPC${scope}`,
+ `Competition${scope}`,
+ "Score",
+ "Intent",
+ ];
+}
+
+export const KEYWORD_RESEARCH_HEADERS = keywordResearchHeaders();
export function keywordResearchExportRow(row: KeywordResearchRow): CsvValue[] {
return [
@@ -59,6 +66,7 @@ export function parseKeywordInput(value: string) {
export function buildKeywordSearchKey(params: {
keyword: string;
locationCode: number | undefined;
+ locationName: string | undefined;
resultLimit: ResultLimit;
mode: KeywordMode;
clickstream: boolean;
@@ -67,6 +75,7 @@ export function buildKeywordSearchKey(params: {
return [
parseKeywordInput(params.keyword).join(""),
params.locationCode,
+ params.locationName,
params.resultLimit,
params.mode,
params.clickstream ? "cs" : "",
@@ -108,17 +117,21 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {
};
const confirmSave = () => {
- const metrics = rows
- .filter((row) => selectedRows.has(row.keyword))
- .map((row) => ({
- keyword: row.keyword,
- searchVolume: row.searchVolume,
- cpc: row.cpc,
- competition: row.competition,
- keywordDifficulty: row.keywordDifficulty,
- intent: row.intent,
- monthlySearches: row.trend,
- }));
+ // Saved keyword metrics are stored per country, so local numbers are not
+ // saved. The saved list keeps the national metrics.
+ const metrics = input.locationName
+ ? undefined
+ : rows
+ .filter((row) => selectedRows.has(row.keyword))
+ .map((row) => ({
+ keyword: row.keyword,
+ searchVolume: row.searchVolume,
+ cpc: row.cpc,
+ competition: row.competition,
+ keywordDifficulty: row.keywordDifficulty,
+ intent: row.intent,
+ monthlySearches: row.trend,
+ }));
saveKeywordsMutate(
{
@@ -150,7 +163,10 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {
toast.error("No data to export");
return;
}
- downloadKeywordResearchCsv(sheetsExportRows);
+ downloadKeywordResearchCsv(
+ sheetsExportRows,
+ keywordResearchHeaders(input.locationName),
+ );
captureClientEvent("data:export", {
source_feature: "keyword_research",
result_count: sheetsExportRows.length,
@@ -160,7 +176,10 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {
return { handleSaveKeywords, confirmSave, exportCsv, sheetsExportRows };
}
-export function downloadKeywordResearchCsv(rows: CsvValue[][]) {
+export function downloadKeywordResearchCsv(
+ rows: CsvValue[][],
+ headers: string[],
+) {
// CSV file keeps cents-formatted CPC/competition for human readability.
const csvRows = rows.map((row) =>
row.map((cell, idx) =>
@@ -169,8 +188,5 @@ export function downloadKeywordResearchCsv(rows: CsvValue[][]) {
: cell,
),
);
- downloadCsv(
- "keyword-research.csv",
- buildCsv(KEYWORD_RESEARCH_HEADERS, csvRows),
- );
+ downloadCsv("keyword-research.csv", buildCsv(headers, csvRows));
}
diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.ts
index 31328dbf..caf6c996 100644
--- a/src/client/features/keywords/state/useKeywordResearchController.ts
+++ b/src/client/features/keywords/state/useKeywordResearchController.ts
@@ -34,6 +34,8 @@ export type KeywordResearchControllerInput = {
keywordInput: string;
locationCode: number | undefined;
displayedLocationCode: number;
+ /** City, county, or region for local volume; undefined for national. */
+ locationName: string | undefined;
setPreferredLocationCode: (locationCode: number) => void;
resultLimit: ResultLimit;
keywordMode: KeywordMode;
@@ -96,7 +98,7 @@ export function useKeywordResearchController(
deepFetchFailed,
retrySerp,
serpError,
- } = useKeywordSerpAnalysis(input.projectId, locationCode);
+ } = useKeywordSerpAnalysis(input.projectId, locationCode, input.locationName);
const {
history,
@@ -123,6 +125,7 @@ export function useKeywordResearchController(
keywordInput: input.keywordInput,
locationCode,
displayedLocationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.keywordMode,
clickstream: input.clickstream,
@@ -137,6 +140,7 @@ export function useKeywordResearchController(
? buildKeywordSearchKey({
keyword: input.keywordInput,
locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.keywordMode,
clickstream: input.clickstream,
@@ -274,6 +278,7 @@ export function useKeywordResearchController(
lastSearchError,
lastSearchKeyword,
lastSearchLocationCode,
+ locationName: input.locationName,
mobileTab: uiState.mobileTab,
overviewKeyword,
removeHistoryItem,
diff --git a/src/client/features/rank-tracking/SearchTargetingField.tsx b/src/client/features/rank-tracking/SearchTargetingField.tsx
index 1b9b5ec7..cd0285aa 100644
--- a/src/client/features/rank-tracking/SearchTargetingField.tsx
+++ b/src/client/features/rank-tracking/SearchTargetingField.tsx
@@ -1,6 +1,5 @@
-import { useQuery } from "@tanstack/react-query";
import { SerpLocationCombobox } from "@/client/components/SerpLocationCombobox";
-import { prewarmSerpLocations } from "@/serverFunctions/serp-locations";
+import { usePrewarmSerpLocations } from "@/client/components/usePrewarmSerpLocations";
type TargetingMode = "national" | "local";
@@ -17,17 +16,8 @@ export function SearchTargetingField({
onLocationNameChange: (locationName: string | undefined) => void;
countryCode: string;
}) {
- // Warm the server-side location cache the moment Local targeting is in
- // play, so the country list is hot before the first keystroke. Best-effort:
- // a failed warm just means the first search is slower, so no retries, and
- // staleTime keeps one warm per country per session.
- useQuery({
- queryKey: ["serp-locations-prewarm", countryCode],
- queryFn: () => prewarmSerpLocations({ data: { countryCode } }),
- enabled: mode === "local",
- staleTime: Infinity,
- retry: false,
- });
+ // Warm the moment Local targeting is in play.
+ usePrewarmSerpLocations(countryCode, mode === "local");
return (
<div className="form-control">
<label className="label">
diff --git a/src/client/features/search-tabs/SearchTabStrip.tsx b/src/client/features/search-tabs/SearchTabStrip.tsx
index 518e4bb0..4d0e69b5 100644
--- a/src/client/features/search-tabs/SearchTabStrip.tsx
+++ b/src/client/features/search-tabs/SearchTabStrip.tsx
@@ -214,6 +214,7 @@ function getSearchTabQueryConfig(
projectId,
keywordInput: input.keyword,
locationCode: input.locationCode,
+ locationName: input.locationName,
resultLimit: input.resultLimit,
mode: input.mode,
clickstream: input.clickstream,
diff --git a/src/client/features/search-tabs/types.ts b/src/client/features/search-tabs/types.ts
index eebbe4b1..e867721e 100644
--- a/src/client/features/search-tabs/types.ts
+++ b/src/client/features/search-tabs/types.ts
@@ -21,6 +21,8 @@ export type KeywordSearchTabInput = {
type: "keyword";
keyword: string;
locationCode?: number;
+ /** City, county, or region for local volume; absent for national. */
+ locationName?: string;
resultLimit: ResultLimit;
mode: KeywordMode;
clickstream: boolean;
diff --git a/src/client/features/search-tabs/useSearchTabs.ts b/src/client/features/search-tabs/useSearchTabs.ts
index d7ce1507..ccbdc4c9 100644
--- a/src/client/features/search-tabs/useSearchTabs.ts
+++ b/src/client/features/search-tabs/useSearchTabs.ts
@@ -106,6 +106,8 @@ function parseTabInput(value: unknown): SearchTabInput | null {
keyword: value.keyword,
locationCode:
typeof value.locationCode === "number" ? value.locationCode : undefined,
+ locationName:
+ typeof value.locationName === "string" ? value.locationName : undefined,
resultLimit: value.resultLimit,
mode: value.mode,
// Tabs persisted before the clickstream toggle existed default to off.
diff --git a/src/client/hooks/useSearchHistory.ts b/src/client/hooks/useSearchHistory.ts
index 5a87c20a..8a70637a 100644
--- a/src/client/hooks/useSearchHistory.ts
+++ b/src/client/hooks/useSearchHistory.ts
@@ -5,7 +5,10 @@ import { jsonCodec } from "@/shared/json";
interface SearchHistoryItem {
keyword: string;
locationCode: number;
+ /** Display label of the searched country, city, county, or region. */
locationName: string;
+ /** Canonical DataForSEO name when the search had local volume. */
+ localLocationName?: string;
timestamp: number;
}
@@ -15,6 +18,7 @@ const searchHistoryItemSchema = z.object({
keyword: z.string(),
locationCode: z.number(),
locationName: z.string(),
+ localLocationName: z.string().optional(),
timestamp: z.number(),
});
@@ -35,7 +39,8 @@ export function useSearchHistory(projectId: string) {
},
isSameItem: (existing, next) =>
existing.keyword === next.keyword &&
- existing.locationCode === next.locationCode,
+ existing.locationCode === next.locationCode &&
+ existing.localLocationName === next.localLocationName,
createItem: (item) => ({
...item,
timestamp: Date.now(),
@@ -46,8 +51,12 @@ export function useSearchHistory(projectId: string) {
return {
history,
isLoaded,
- addSearch: (keyword: string, locationCode: number, locationName: string) =>
- addItem({ keyword, locationCode, locationName }),
+ addSearch: (
+ keyword: string,
+ locationCode: number,
+ locationName: string,
+ localLocationName: string | undefined,
+ ) => addItem({ keyword, locationCode, locationName, localLocationName }),
clearHistory: clearItems,
removeHistoryItem: removeItem,
};
diff --git a/src/client/lib/error-messages.ts b/src/client/lib/error-messages.ts
index 09973b36..b570ba4a 100644
--- a/src/client/lib/error-messages.ts
+++ b/src/client/lib/error-messages.ts
@@ -17,6 +17,8 @@ const STANDARD_MESSAGES: Record<ErrorCode, string> = {
AUDIT_ALREADY_RUNNING:
"You've reached the limit of audits running at once. Wait for one to finish or delete it before starting another.",
VALIDATION_ERROR: "Please check your input and try again.",
+ UNKNOWN_LOCATION:
+ "We couldn't find that city, county, or region. Pick a location from the list, or clear the field to search the whole country.",
CRAWL_TARGET_BLOCKED: "This crawl target is blocked by security policy.",
BACKLINKS_BILLING_ISSUE:
"The connected DataForSEO account has a billing or balance issue.",
diff --git a/src/routes/_project/p/$projectId/keywords.tsx b/src/routes/_project/p/$projectId/keywords.tsx
index 6dbca314..5d502f26 100644
--- a/src/routes/_project/p/$projectId/keywords.tsx
+++ b/src/routes/_project/p/$projectId/keywords.tsx
@@ -41,6 +41,7 @@ function KeywordResearchPageRoute() {
projectId={projectId}
keywordInput={keywordInput}
locationCode={locationCode}
+ locationName={search.locName}
resultLimit={isResultLimit(resultLimit) ? resultLimit : 150}
keywordMode={normalizeKeywordMode(keywordMode)}
clickstream={search.cs ?? false}
diff --git a/src/server/features/keywords/services/research/local-volume.ts b/src/server/features/keywords/services/research/local-volume.ts
new file mode 100644
index 00000000..18d3c0c4
--- /dev/null
+++ b/src/server/features/keywords/services/research/local-volume.ts
@@ -0,0 +1,77 @@
+import type { BillingCustomerContext } from "@/server/billing/subscription";
+import type { CreditFeature } from "@/shared/billing-credit-features";
+import { createDataforseoClient } from "@/server/lib/dataforseo";
+import { fetchAdsSearchVolumeForKeywords } from "@/server/lib/dataforseo/keyword-metrics";
+import { fetchSerpLocationsForCountry } from "@/server/lib/dataforseo/serp-locations";
+import { AppError } from "@/server/lib/errors";
+import {
+ LOCATION_OPTIONS,
+ formatLocationLabel,
+ getIsoCountryCode,
+} from "@/shared/keyword-locations";
+import type { EnrichedKeyword } from "./helpers";
+import { mapAdsKeywordItems } from "./research-data";
+
+/**
+ * Reject a location that is not a city, county, or region of the country
+ * before any paid call runs. The registry is the same list the location
+ * picker searches, so it also keeps postal codes out.
+ */
+export async function assertLocalResearchLocation(
+ locationCode: number,
+ locationName: string,
+): Promise<void> {
+ const locations = await fetchSerpLocationsForCountry(
+ getIsoCountryCode(locationCode),
+ );
+ if (locations.some((location) => location.locationName === locationName)) {
+ return;
+ }
+ const country =
+ LOCATION_OPTIONS.find((option) => option.code === locationCode)?.label ??
+ "this country";
+ // The app shows a fixed message for this code; MCP callers get this one.
+ throw new AppError(
+ "UNKNOWN_LOCATION",
+ `"${formatLocationLabel(locationName)}" is not a city, county, or region we can find in ${country}.`,
+ );
+}
+
+/**
+ * Replace each row's volume, trend, CPC, and competition with Google Ads
+ * numbers for one city, county, or region. Keyword difficulty and intent stay
+ * national: Labs only serves countries. A keyword Google Ads does not return
+ * (collapsed close variants, or text Ads rejects) gets null metrics, never the
+ * national numbers.
+ */
+export async function localizeResearchRows(
+ rows: EnrichedKeyword[],
+ params: {
+ locationCode: number;
+ locationName: string;
+ languageCode: string;
+ creditFeature?: CreditFeature;
+ },
+ billingCustomer: BillingCustomerContext,
+): Promise<EnrichedKeyword[]> {
+ // Research results cap at 500 rows, under the endpoint's 1,000 keyword
+ // limit, so one call covers them.
+ const items = await fetchAdsSearchVolumeForKeywords(
+ createDataforseoClient(billingCustomer),
+ { ...params, keywords: rows.map((row) => row.keyword) },
+ );
+ const localByKeyword = new Map(
+ mapAdsKeywordItems(items).map((local) => [local.keyword, local]),
+ );
+
+ return rows.map((row) => {
+ const local = localByKeyword.get(row.keyword);
+ return {
+ ...row,
+ searchVolume: local?.searchVolume ?? null,
+ trend: local?.trend ?? [],
+ cpc: local?.cpc ?? null,
+ competition: local?.competition ?? null,
+ };
+ });
+}
diff --git a/src/server/features/keywords/services/research/research.test.ts b/src/server/features/keywords/services/research/research.test.ts
index 1a14e368..0bbe07c1 100644
--- a/src/server/features/keywords/services/research/research.test.ts
+++ b/src/server/features/keywords/services/research/research.test.ts
@@ -4,10 +4,12 @@ import { EMPTY_FILTERS } from "@/client/features/keywords/keywordResearchTypes";
import { applyKeywordFiltersAndSort } from "@/client/features/keywords/hooks/useKeywordFiltering";
import { buildCacheKey } from "@/server/lib/r2-cache";
import { research } from "./research";
+import type * as ResearchData from "./research-data";
const mocks = vi.hoisted(() => ({
cache: new Map<string, string>(),
fetchRows: vi.fn(),
+ adsSearchVolume: vi.fn(),
upsertKeywordMetric: vi.fn().mockResolvedValue(undefined),
}));
@@ -20,12 +22,29 @@ vi.mock("cloudflare:workers", () => ({
},
put: async (key: string, value: string) => mocks.cache.set(key, value),
},
+ KV: {
+ get: async () => [
+ {
+ locationCode: 1026201,
+ locationName: "Austin,Texas,United States",
+ locationType: "City",
+ displayLabel: "Austin, Texas, United States",
+ },
+ ],
+ },
},
}));
-vi.mock("./research-data", () => ({
+vi.mock("./research-data", async (importOriginal) => ({
+ mapAdsKeywordItems: (await importOriginal<typeof ResearchData>())
+ .mapAdsKeywordItems,
fetchResearchRowsBySource: mocks.fetchRows,
fetchGoogleAdsResearchRows: vi.fn(),
}));
+vi.mock("@/server/lib/dataforseo", () => ({
+ createDataforseoClient: () => ({
+ keywords: { adsSearchVolume: mocks.adsSearchVolume },
+ }),
+}));
vi.mock(
"@/server/features/keywords/repositories/KeywordResearchRepository",
() => ({
@@ -35,6 +54,12 @@ vi.mock(
}),
);
+const customer = {
+ organizationId: "org_1",
+ userId: "user_1",
+ userEmail: "[email protected]",
+};
+
it("keeps shared-volume keywords independently filterable through research and cache", async () => {
const seed: KeywordResearchRow = {
keyword: "caregiving",
@@ -77,11 +102,6 @@ it("keeps shared-volume keywords independently filterable through research and c
clickstream: false,
groupKeywords: true,
};
- const customer = {
- organizationId: "org_1",
- userId: "user_1",
- userEmail: "[email protected]",
- };
// An older cached grouping must not hide the opportunity after this fix.
const oldKey = await buildCacheKey("kw:research", {
...input,
@@ -134,3 +154,114 @@ it("keeps shared-volume keywords independently filterable through research and c
expect(await research(input, customer)).toEqual(fresh);
expect(mocks.fetchRows).toHaveBeenCalledTimes(5);
});
+
+const nationalPlumber: KeywordResearchRow = {
+ keyword: "plumber",
+ searchVolume: 673000,
+ trend: [{ year: 2026, month: 8, searchVolume: 673000 }],
+ cpc: 34.32,
+ competition: 0.1,
+ keywordDifficulty: 31,
+ intent: "commercial",
+};
+
+const localInput = {
+ projectId: "project_1",
+ keywords: ["plumber"],
+ locationCode: 2840,
+ languageCode: "en",
+ locationName: "Austin,Texas,United States",
+ resultLimit: 150 as const,
+ mode: "suggestions" as const,
+ clickstream: true,
+ groupKeywords: false,
+};
+
+it("replaces national volume with local volume and never falls back to national", async () => {
+ const collapsed = { ...nationalPlumber, keyword: "plumbers" };
+ const adsRejected = { ...nationalPlumber, keyword: "plumber (24/7)" };
+ mocks.fetchRows.mockResolvedValue([nationalPlumber, collapsed, adsRejected]);
+ mocks.adsSearchVolume.mockResolvedValue([
+ {
+ keyword: "plumber",
+ search_volume: 2900,
+ cpc: 36.67,
+ competition_index: 20,
+ monthly_searches: [{ year: 2026, month: 8, search_volume: 2900 }],
+ },
+ ]);
+
+ const result = await research(localInput, customer);
+
+ expect(result.rows).toEqual([
+ {
+ ...nationalPlumber,
+ searchVolume: 2900,
+ trend: [{ year: 2026, month: 8, searchVolume: 2900 }],
+ cpc: 36.67,
+ competition: 0.2,
+ },
+ ...[collapsed, adsRejected].map((row) => ({
+ ...row,
+ searchVolume: null,
+ trend: [],
+ cpc: null,
+ competition: null,
+ })),
+ ]);
+ // Local volume replaces clickstream volume, so the national leg skips it.
+ expect(mocks.fetchRows.mock.calls[0][0]).toMatchObject({
+ includeClickstreamData: false,
+ });
+ expect(mocks.adsSearchVolume).toHaveBeenCalledWith(
+ expect.objectContaining({
+ keywords: ["plumber", "plumbers"],
+ locationName: "Austin,Texas,United States",
+ }),
+ );
+ // Keyword metrics are stored per country: only national numbers persist.
+ expect(mocks.upsertKeywordMetric).toHaveBeenCalledWith(
+ expect.objectContaining({ keyword: "plumber", searchVolume: 673000 }),
+ );
+ expect(mocks.upsertKeywordMetric).not.toHaveBeenCalledWith(
+ expect.objectContaining({ searchVolume: 2900 }),
+ );
+
+ expect(await research(localInput, customer)).toEqual(result);
+ expect(mocks.adsSearchVolume).toHaveBeenCalledTimes(1);
+});
+
+it("stores national metrics for a local search whose national result is cached", async () => {
+ const nationalInput = {
+ ...localInput,
+ keywords: ["electrician"],
+ locationName: undefined,
+ clickstream: false,
+ };
+ mocks.fetchRows.mockResolvedValue([
+ { ...nationalPlumber, keyword: "electrician", searchVolume: 90500 },
+ ]);
+ mocks.adsSearchVolume.mockResolvedValue([]);
+ await research(nationalInput, customer);
+ const callsAfterNational = mocks.upsertKeywordMetric.mock.calls.length;
+
+ await research(
+ { ...nationalInput, locationName: localInput.locationName },
+ customer,
+ );
+
+ expect(mocks.fetchRows).toHaveBeenCalledTimes(1);
+ expect(
+ mocks.upsertKeywordMetric.mock.calls.slice(callsAfterNational),
+ ).toEqual([
+ [expect.objectContaining({ keyword: "electrician", searchVolume: 90500 })],
+ ]);
+});
+
+it("rejects a location outside the country's registry before any paid call", async () => {
+ await expect(
+ research({ ...localInput, locationName: "Austin, TX" }, customer),
+ ).rejects.toMatchObject({ code: "UNKNOWN_LOCATION" });
+ expect(mocks.fetchRows).not.toHaveBeenCalled();
+ expect(mocks.adsSearchVolume).not.toHaveBeenCalled();
+});
diff --git a/src/server/features/keywords/services/research/research.ts b/src/server/features/keywords/services/research/research.ts
index 4663126e..5edbf0c8 100644
--- a/src/server/features/keywords/services/research/research.ts
+++ b/src/server/features/keywords/services/research/research.ts
@@ -17,6 +17,10 @@ import {
normalizeKeyword,
type EnrichedKeyword,
} from "./helpers";
+import {
+ assertLocalResearchLocation,
+ localizeResearchRows,
+} from "./local-volume";
import {
fetchGoogleAdsResearchRows,
fetchResearchRowsBySource,
@@ -220,14 +224,15 @@ async function buildResearchCacheKey(
depth: 3,
clickstream: input.clickstream,
groupKeywords: input.groupKeywords,
+ locationName: input.locationName,
});
}
function persistRows(
input: ResolvedResearchKeywordsInput,
rows: EnrichedKeyword[],
-) {
- void Promise.all(
+): Promise<void> {
+ return Promise.all(
rows.map((row) =>
KeywordResearchRepository.upsertKeywordMetric({
projectId: input.projectId,
@@ -242,9 +247,12 @@ function persistRows(
monthlySearchesJson: JSON.stringify(row.trend),
}),
),
- ).catch((error) => {
- console.error("keywords.research.persist-metrics failed:", error);
- });
+ ).then(
+ () => undefined,
+ (error: unknown) => {
+ console.error("keywords.research.persist-metrics failed:", error);
+ },
+ );
}
export async function research(
@@ -264,11 +272,14 @@ export async function research(
const provider = getKeywordDataProvider(input.locationCode);
// Labs source modes, clickstream, and synonym filtering don't exist for
// Google-Ads-served countries; normalize them so equivalent requests share
- // one cache entry.
+ // one cache entry. Local volume replaces the clickstream volume, so a local
+ // request never pays for clickstream.
const effectiveInput: ResolvedResearchKeywordsInput =
provider === "google_ads"
? { ...input, mode: "auto", clickstream: false, groupKeywords: false }
- : input;
+ : input.locationName
+ ? { ...input, clickstream: false }
+ : input;
const mode = effectiveInput.mode ?? "auto";
const cacheKey = await buildResearchCacheKey(
effectiveInput,
@@ -287,8 +298,14 @@ export async function research(
return cached;
}
- const result =
- provider === "google_ads"
+ const result = effectiveInput.locationName
+ ? await researchLocal(
+ effectiveInput,
+ effectiveInput.locationName,
+ billingCustomer,
+ creditFeature,
+ )
+ : provider === "google_ads"
? await fetchGoogleAdsRows(
effectiveInput,
seedKeyword,
@@ -311,7 +328,46 @@ export async function research(
);
await setCached(cacheKey, result, CACHE_TTL.researchResult);
- persistRows(effectiveInput, result.rows);
+ // Keyword metrics are stored per country, so local rows are not persisted.
+ if (!effectiveInput.locationName)
+ void persistRows(effectiveInput, result.rows);
return result;
}
+
+/**
+ * Keyword ideas, difficulty, and intent come from the national research
+ * (cached and persisted as usual). One Google Ads call then replaces volume,
+ * CPC, and competition with numbers for the city, county, or region.
+ */
+async function researchLocal(
+ input: ResolvedResearchKeywordsInput,
+ locationName: string,
+ billingCustomer: BillingCustomerContext,
+ creditFeature?: CreditFeature,
+): Promise<ResearchResult> {
+ await assertLocalResearchLocation(input.locationCode, locationName);
+ const nationalInput = { ...input, locationName: undefined };
+ const national = await research(
+ nationalInput,
+ billingCustomer,
+ creditFeature,
+ );
+ // A save from local results sends no metrics, so the saved keyword relies on
+ // the stored national ones. Store them before returning, also when the
+ // national result came from the cache.
+ await persistRows(nationalInput, national.rows);
+ return {
+ ...national,
+ rows: await localizeResearchRows(
+ national.rows,
+ {
+ locationCode: input.locationCode,
+ locationName,
+ languageCode: input.languageCode,
+ creditFeature,
+ },
+ billingCustomer,
+ ),
+ };
+}
diff --git a/src/server/features/keywords/services/research/serp.test.ts b/src/server/features/keywords/services/research/serp.test.ts
index cc7d6ddf..fe512c55 100644
--- a/src/server/features/keywords/services/research/serp.test.ts
+++ b/src/server/features/keywords/services/research/serp.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from "vitest";
import type { BillingCustomerContext } from "@/server/billing/subscription";
const mocks = vi.hoisted(() => ({
+ assertLocalResearchLocation: vi.fn(async () => {}),
+ buildCacheKey: vi.fn(async () => "serp:analysis:key"),
createDataforseoClient: vi.fn(),
getCached: vi.fn(),
setCached: vi.fn(async () => {}),
@@ -10,11 +12,15 @@ const mocks = vi.hoisted(() => ({
vi.mock("cloudflare:workers", () => ({ waitUntil: vi.fn() }));
vi.mock("@/server/lib/r2-cache", () => ({
- buildCacheKey: vi.fn(async () => "serp:analysis:key"),
+ buildCacheKey: mocks.buildCacheKey,
getCached: mocks.getCached,
setCached: mocks.setCached,
}));
+vi.mock("./local-volume", () => ({
+ assertLocalResearchLocation: mocks.assertLocalResearchLocation,
+}));
+
vi.mock("@/server/lib/dataforseo", () => ({
SERP_ANALYSIS_DEPTH: 20,
createDataforseoClient: mocks.createDataforseoClient,
@@ -121,4 +127,28 @@ describe("getSerpAnalysis cache depth", () => {
expect.any(Number),
);
});
+
+ it("fetches and caches the SERP for the selected area", async () => {
+ mocks.getCached.mockResolvedValue(null);
+ const live = mockLiveSerp();
+ const locationName = "Austin,Texas,United States";
+
+ await getSerpAnalysis(
+ { ...input, depth: 20, locationName },
+ billingCustomer,
+ );
+
+ expect(mocks.assertLocalResearchLocation).toHaveBeenCalledWith(
+ 2840,
+ locationName,
+ );
+ expect(live).toHaveBeenCalledWith(
+ expect.objectContaining({ locationName }),
+ );
+ // A national snapshot must never answer a local request.
+ expect(mocks.buildCacheKey).toHaveBeenCalledWith(
+ "serp:analysis",
+ expect.objectContaining({ locationName }),
+ );
+ });
});
diff --git a/src/server/features/keywords/services/research/serp.ts b/src/server/features/keywords/services/research/serp.ts
index 96bbe8a5..d2c438b5 100644
--- a/src/server/features/keywords/services/research/serp.ts
+++ b/src/server/features/keywords/services/research/serp.ts
@@ -9,6 +9,7 @@ import { z } from "zod";
import type { BillingCustomerContext } from "@/server/billing/subscription";
import { createDataforseoClient } from "@/server/lib/dataforseo";
import { normalizeKeyword } from "./helpers";
+import { assertLocalResearchLocation } from "./local-volume";
const SERP_CACHE_TTL_SECONDS = 12 * 60 * 60;
@@ -71,11 +72,15 @@ async function getSerpLiveAnalysis(
locationCode: number;
languageCode: string;
depth: number;
+ locationName?: string;
},
billingCustomer: BillingCustomerContext,
): Promise<SerpAnalysisResult> {
const keyword = normalizeKeyword(input.keyword);
const { depth } = input;
+ if (input.locationName) {
+ await assertLocalResearchLocation(input.locationCode, input.locationName);
+ }
const cacheKey = await buildCacheKey("serp:analysis", {
organizationId: billingCustomer.organizationId,
@@ -83,6 +88,7 @@ async function getSerpLiveAnalysis(
keyword,
locationCode: input.locationCode,
languageCode: input.languageCode,
+ locationName: input.locationName,
});
// Depth lives in the cached value, not the key: DataForSEO has no offset, so
@@ -99,6 +105,7 @@ async function getSerpLiveAnalysis(
keyword,
locationCode: input.locationCode,
languageCode: input.languageCode,
+ locationName: input.locationName,
depth,
});
diff --git a/src/server/lib/dataforseo/google-ads.ts b/src/server/lib/dataforseo/google-ads.ts
index fb3d19a4..65389d8f 100644
--- a/src/server/lib/dataforseo/google-ads.ts
+++ b/src/server/lib/dataforseo/google-ads.ts
@@ -31,6 +31,21 @@ function taskItems<T>(task: KeywordsDataTask<T>): T[] {
return task.result ?? [];
}
+// Google Ads fails the whole search_volume task when one keyword has one of
+// these symbols or an emoji, is longer than 80 characters, or has more than
+// 10 words.
+const ADS_INVALID_KEYWORD_CHARS =
+ /[!@%,*(){}<>|^~;=?`]|\p{Extended_Pictographic}/u;
+
+/** Whether Google Ads search_volume accepts this keyword text. */
+export function isAdsKeyword(keyword: string): boolean {
+ return (
+ keyword.length <= 80 &&
+ keyword.split(/\s+/).length <= 10 &&
+ !ADS_INVALID_KEYWORD_CHARS.test(keyword)
+ );
+}
+
export async function fetchAdsSearchVolume(input: {
keywords: string[];
locationCode: number;
diff --git a/src/server/lib/dataforseo/keyword-metrics.test.ts b/src/server/lib/dataforseo/keyword-metrics.test.ts
index 8a4b88f6..299db1c4 100644
--- a/src/server/lib/dataforseo/keyword-metrics.test.ts
+++ b/src/server/lib/dataforseo/keyword-metrics.test.ts
@@ -108,6 +108,29 @@ describe("fetchKeywordMetricsForList", () => {
]);
});
+ it("skips keywords Google Ads rejects instead of failing the batch", async () => {
+ const adsSearchVolume = vi.fn().mockResolvedValue([]);
+
+ const rows = await fetchKeywordMetricsForList(
+ fakeClient({ adsSearchVolume }),
+ {
+ keywords: ["hotel reykjavik", "hotel (cheap)", "best hotel?"],
+ locationCode: 2352,
+ languageCode: "is",
+ creditFeature: "rank_tracking",
+ },
+ );
+
+ expect(adsSearchVolume).toHaveBeenCalledWith(
+ expect.objectContaining({ keywords: ["hotel reykjavik"] }),
+ );
+ // Rejected keywords get empty metrics, so a refresh clears stale values.
+ expect(rows).toEqual([
+ expect.objectContaining({ keyword: "hotel (cheap)", searchVolume: null }),
+ expect.objectContaining({ keyword: "best hotel?", searchVolume: null }),
+ ]);
+ });
+
it("batches keyword lists above the per-call cap", async () => {
const keywordOverview = vi
.fn()
@@ -159,7 +182,11 @@ describe("fetchKeywordMetricsForList", () => {
const client = fakeClient({ adsSearchVolume, keywordOverview });
const rows = await fetchKeywordMetricsForList(client, {
- keywords: ["plumber near me", "emergency plumber near me"],
+ keywords: [
+ "plumber near me",
+ "emergency plumber near me",
+ "plumber (24/7)",
+ ],
locationCode: 2840,
languageCode: "en",
locationName: "Springfield,Illinois,United States",
@@ -188,5 +215,11 @@ describe("fetchKeywordMetricsForList", () => {
keywordDifficulty: 17,
intent: "transactional",
});
+ // Neither source returned it: an empty row still clears stale metrics.
+ expect(rows[2]).toMatchObject({
+ keyword: "plumber (24/7)",
+ searchVolume: null,
+ keywordDifficulty: null,
+ });
});
});
diff --git a/src/server/lib/dataforseo/keyword-metrics.ts b/src/server/lib/dataforseo/keyword-metrics.ts
index 6af3107c..cd67afaa 100644
--- a/src/server/lib/dataforseo/keyword-metrics.ts
+++ b/src/server/lib/dataforseo/keyword-metrics.ts
@@ -1,5 +1,8 @@
import type { createDataforseoClient } from "@/server/lib/dataforseo/client";
-import type { AdsKeywordItem } from "@/server/lib/dataforseo/google-ads";
+import {
+ isAdsKeyword,
+ type AdsKeywordItem,
+} from "@/server/lib/dataforseo/google-ads";
import type { KeywordOverviewItem } from "@/server/lib/dataforseo/labs";
import type { CreditFeature } from "@/shared/billing-credit-features";
import { getKeywordDataProvider } from "@/shared/keyword-locations";
@@ -13,6 +16,20 @@ type KeywordMetricsClient = {
keywords: Pick<DataforseoClient["keywords"], "adsSearchVolume">;
};
+/**
+ * Google Ads search volume for the keywords Ads accepts. One rejected keyword
+ * fails the whole task, so rejected ones are skipped and get no Ads metrics.
+ */
+export async function fetchAdsSearchVolumeForKeywords(
+ client: KeywordMetricsClient,
+ params: Parameters<KeywordMetricsClient["keywords"]["adsSearchVolume"]>[0],
+): Promise<AdsKeywordItem[]> {
+ const keywords = params.keywords.filter(isAdsKeyword);
+ return keywords.length > 0
+ ? client.keywords.adsSearchVolume({ ...params, keywords })
+ : [];
+}
+
// DataForSEO's batch metric endpoints accept up to ~700 keywords per request.
const KEYWORD_METRICS_BATCH_SIZE = 700;
@@ -121,7 +138,7 @@ export async function fetchKeywordMetricsForList(
const keywords = params.keywords.slice(i, i + KEYWORD_METRICS_BATCH_SIZE);
if (useGoogleAds) {
- const items = await client.keywords.adsSearchVolume({
+ const items = await fetchAdsSearchVolumeForKeywords(client, {
keywords,
locationCode: params.locationCode,
locationName: params.locationName,
@@ -134,19 +151,23 @@ export async function fetchKeywordMetricsForList(
covered.add(item.keyword.toLowerCase());
rows.push(normalizeAdsKeyword(item, item.keyword));
}
- if (params.locationName) {
- // A local request must overwrite whatever scope the stored metrics
- // had — keywords Ads collapsed away get explicit nulls so stale
- // (possibly national) numbers can't survive under a local label.
- rows.push(
- ...keywords
- .filter((keyword) => !covered.has(keyword.toLowerCase()))
- .map(nullMetricRow),
- );
- }
+ // A local request must overwrite whatever scope the stored metrics
+ // had — keywords Ads collapsed away get explicit nulls so stale
+ // (possibly national) numbers can't survive under a local label.
+ // Keywords Ads rejects can never have Ads metrics, so they get nulls
+ // on every request.
+ rows.push(
+ ...keywords
+ .filter(
+ (keyword) =>
+ !covered.has(keyword.toLowerCase()) &&
+ (params.locationName || !isAdsKeyword(keyword)),
+ )
+ .map(nullMetricRow),
+ );
} else if (params.locationName) {
const [adsItems, labsItems] = await Promise.all([
- client.keywords.adsSearchVolume({
+ fetchAdsSearchVolumeForKeywords(client, {
keywords,
locationCode: params.locationCode,
locationName: params.locationName,
@@ -220,14 +241,15 @@ function mergeLocalAndNationalRows(
// Google Ads occasionally collapses near-duplicate keywords into one item.
// Keep the national KD / intent for the missing ones but leave volume / CPC
// null rather than substituting the (misleading) national numbers.
+ // Every keyword gets a row, so a refresh clears stale stored metrics even
+ // when neither source returned it (e.g. text Google Ads rejects).
for (const keyword of keywords) {
if (covered.has(keyword.toLowerCase())) continue;
const labs = labsByKeyword.get(keyword.toLowerCase());
- if (!labs) continue;
rows.push({
...nullMetricRow(keyword),
- keywordDifficulty: labs.keyword_properties?.keyword_difficulty ?? null,
- intent: labs.search_intent_info?.main_intent ?? null,
+ keywordDifficulty: labs?.keyword_properties?.keyword_difficulty ?? null,
+ intent: labs?.search_intent_info?.main_intent ?? null,
});
}
diff --git a/src/server/lib/dataforseo/serp.ts b/src/server/lib/dataforseo/serp.ts
index 850601fc..b78ebb14 100644
--- a/src/server/lib/dataforseo/serp.ts
+++ b/src/server/lib/dataforseo/serp.ts
@@ -88,13 +88,18 @@ export async function fetchLiveSerp(input: {
locationCode: number;
languageCode: string;
depth?: number;
+ /** Canonical DataForSEO name of a city, county, or region for a local SERP. */
+ locationName?: string;
}): Promise<DataforseoApiResponse<SerpLiveItem[]>> {
+ const locationParams = input.locationName
+ ? { location_name: input.locationName }
+ : { location_code: input.locationCode };
const response = await dataforseoPost(
"/v3/serp/google/organic/live/advanced",
[
{
keyword: input.keyword,
- location_code: input.locationCode,
+ ...locationParams,
language_code: input.languageCode,
device: "desktop",
os: "windows",
diff --git a/src/server/lib/http-errors.ts b/src/server/lib/http-errors.ts
index d87c2890..bf05183e 100644
--- a/src/server/lib/http-errors.ts
+++ b/src/server/lib/http-errors.ts
@@ -9,6 +9,7 @@ function statusForAppError(code: string): number {
case "NOT_FOUND":
return 404;
case "VALIDATION_ERROR":
+ case "UNKNOWN_LOCATION":
return 400;
case "PAYMENT_REQUIRED":
return 402;
diff --git a/src/server/mcp/tool-error-message.ts b/src/server/mcp/tool-error-message.ts
new file mode 100644
index 00000000..048a9088
--- /dev/null
+++ b/src/server/mcp/tool-error-message.ts
@@ -0,0 +1,12 @@
+import { AppError } from "@/server/lib/errors";
+
+/**
+ * Error text for a tool call that took a `locationName`. An unknown area
+ * also tells the agent how to find a valid one.
+ */
+export function toolErrorMessage(error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error);
+ return error instanceof AppError && error.code === "UNKNOWN_LOCATION"
+ ? `${message} Call search_serp_locations and pass the returned locationName exactly.`
+ : message;
+}
diff --git a/src/server/mcp/tools/get-serp-results.ts b/src/server/mcp/tools/get-serp-results.ts
index 66a8bf0c..c7e0b714 100644
--- a/src/server/mcp/tools/get-serp-results.ts
+++ b/src/server/mcp/tools/get-serp-results.ts
@@ -8,6 +8,8 @@ import { buildProjectMeta } from "@/server/mcp/context";
import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { resolveMarket } from "@/shared/keyword-locations";
+import { assertLocalResearchLocation } from "@/server/features/keywords/services/research/local-volume";
+import { toolErrorMessage } from "@/server/mcp/tool-error-message";
import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
import {
languageCodeSchema,
@@ -35,6 +37,13 @@ const querySchema = z.object({
keyword: z.string().min(1).describe("Search query to fetch the SERP for."),
locationCode: locationCodeSchema.optional(),
languageCode: languageCodeSchema.optional(),
+ locationName: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ "Optional city, county, or region inside the query's country, for a local SERP. Call search_serp_locations first and pass its locationName verbatim. Same price as a national SERP.",
+ ),
});
const inputSchema = {
@@ -111,9 +120,17 @@ export const getSerpResultsTool = {
const results = await Promise.all(
args.queries.map(async (q) => {
try {
+ const market = resolveMarket(q, context.project);
+ if (q.locationName) {
+ await assertLocalResearchLocation(
+ market.locationCode,
+ q.locationName,
+ );
+ }
const items = await client.serp.live({
keyword: q.keyword,
- ...resolveMarket(q, context.project),
+ ...market,
+ locationName: q.locationName,
depth,
});
// Trim noise — return only essentials per item.
@@ -130,7 +147,7 @@ export const getSerpResultsTool = {
return {
keyword: q.keyword,
ok: false as const,
- error: error instanceof Error ? error.message : String(error),
+ error: toolErrorMessage(error),
};
}
}),
diff --git a/src/server/mcp/tools/research-keywords.test.ts b/src/server/mcp/tools/research-keywords.test.ts
index 022d9d89..5cd2cd20 100644
--- a/src/server/mcp/tools/research-keywords.test.ts
+++ b/src/server/mcp/tools/research-keywords.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { researchKeywordsTool } from "./research-keywords";
+import { AppError } from "@/server/lib/errors";
import { makeToolContext } from "./tool-test-support";
const mocks = vi.hoisted(() => ({
@@ -70,4 +71,27 @@ describe("research_keywords", () => {
},
]);
});
+
+ it("tells an agent how to find a valid local location", async () => {
+ mocks.research.mockRejectedValue(
+ new AppError("UNKNOWN_LOCATION", "Not a known area."),
+ );
+
+ const result = await researchKeywordsTool.handler(
+ {
+ projectId: "project_1",
+ seeds: [{ seed: "plumber", locationName: "Austin, TX" }],
+ },
+ makeToolContext(),
+ );
+
+ expect(result.structuredContent?.results).toEqual([
+ {
+ seed: "plumber",
+ ok: false,
+ error:
+ "Not a known area. Call search_serp_locations and pass the returned locationName exactly.",
+ },
+ ]);
+ });
});
diff --git a/src/server/mcp/tools/research-keywords.ts b/src/server/mcp/tools/research-keywords.ts
index 57f24e3b..55014df3 100644
--- a/src/server/mcp/tools/research-keywords.ts
+++ b/src/server/mcp/tools/research-keywords.ts
@@ -11,16 +11,34 @@ import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { resolveMarket } from "@/shared/keyword-locations";
import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
import { assertLanguageForLocation } from "@/server/lib/market";
+import { toolErrorMessage } from "@/server/mcp/tool-error-message";
+import {
+ AUTUMN_SEO_DATA_CREDITS_PER_USD,
+ LOCAL_VOLUME_COST_USD,
+ applyBillingMarkupUsd,
+} from "@/shared/billing";
import {
languageCodeSchema,
locationCodeSchema,
projectIdSchema,
} from "@/server/mcp/schemas";
+const LOCAL_VOLUME_CREDITS = Math.ceil(
+ applyBillingMarkupUsd(LOCAL_VOLUME_COST_USD) *
+ AUTUMN_SEO_DATA_CREDITS_PER_USD,
+);
+
const seedSchema = z.object({
seed: z.string().min(1).describe("Seed keyword to research."),
locationCode: locationCodeSchema.optional(),
languageCode: languageCodeSchema.optional(),
+ locationName: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ `Optional city, county, or region inside the seed's country, for local search volume. Call search_serp_locations first and pass its locationName verbatim. Volume, CPC, and competition then come from Google Ads for that area; keyword ideas, KD, and intent stay national. Adds ~${LOCAL_VOLUME_CREDITS} credits per seed.`,
+ ),
});
const inputSchema = {
@@ -141,6 +159,7 @@ export const researchKeywordsTool = {
keywords: [item.seed],
locationCode,
languageCode,
+ locationName: item.locationName,
resultLimit: args.resultLimit ?? 150,
mode: "auto",
clickstream: args.includeClickstreamData ?? false,
@@ -151,6 +170,7 @@ export const researchKeywordsTool = {
return {
seed: item.seed,
ok: true as const,
+ locationName: item.locationName,
rowCount: data.rows.length,
source: data.source,
usedFallback: data.usedFallback,
@@ -160,7 +180,7 @@ export const researchKeywordsTool = {
return {
seed: item.seed,
ok: false as const,
- error: error instanceof Error ? error.message : String(error),
+ error: toolErrorMessage(error),
};
}
}),
@@ -174,7 +194,10 @@ export const researchKeywordsTool = {
if (!r.ok) {
return `## "${r.seed}" — FAILED\n${r.error}`;
}
- const header = `## "${r.seed}" — ${r.rowCount} keywords (source: ${r.source}${r.usedFallback ? ", fallback" : ""})`;
+ const scope = r.locationName
+ ? `, volume/CPC/competition for ${r.locationName}, KD/intent national`
+ : "";
+ const header = `## "${r.seed}" — ${r.rowCount} keywords (source: ${r.source}${r.usedFallback ? ", fallback" : ""}${scope})`;
if (r.rowCount === 0) {
return `${header}\n(no keywords returned)`;
}
diff --git a/src/server/mcp/tools/search-serp-locations.ts b/src/server/mcp/tools/search-serp-locations.ts
index 9247b6f6..f847f883 100644
--- a/src/server/mcp/tools/search-serp-locations.ts
+++ b/src/server/mcp/tools/search-serp-locations.ts
@@ -23,7 +23,7 @@ export const searchSerpLocationsTool = {
config: {
title: "Search SERP locations",
description:
- "Find the exact DataForSEO location name for local rank tracking. Returns up to 10 matches; pass the chosen `locationName` verbatim to create_rank_tracker. Uses no credits.",
+ "Find the exact DataForSEO location name of a city, county, or region. Returns up to 10 matches; pass the chosen `locationName` verbatim to create_rank_tracker for local rank tracking, or to research_keywords for local search volume. Uses no credits.",
inputSchema,
outputSchema: z.looseObject({
locations: z.array(
diff --git a/src/shared/billing.ts b/src/shared/billing.ts
index f5cfe524..100bc3dc 100644
--- a/src/shared/billing.ts
+++ b/src/shared/billing.ts
@@ -17,6 +17,9 @@ export const AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID = "topup_credits";
export const AUTUMN_SEO_DATA_CREDITS_PER_USD = 1000;
export const SEO_DATA_COST_MARKUP = 1.28;
export const LOW_CREDITS_THRESHOLD_USD = 0.25;
+// DataForSEO's raw price for one Google Ads search_volume live call (up to
+// 1,000 keywords). Local keyword research adds one call to each search.
+export const LOCAL_VOLUME_COST_USD = 0.09;
// Passed through to Stripe's checkout.sessions.create so checkout collects the
// legal business name, tax ID (EU VAT etc.), and full billing address — makes
diff --git a/src/shared/error-codes.test.ts b/src/shared/error-codes.test.ts
index 085f2752..82ef6486 100644
--- a/src/shared/error-codes.test.ts
+++ b/src/shared/error-codes.test.ts
@@ -7,6 +7,7 @@ describe("shouldCaptureAppErrorCode", () => {
"NOT_FOUND",
"PAYMENT_REQUIRED",
"VALIDATION_ERROR",
+ "UNKNOWN_LOCATION",
"AUDIT_CAPACITY_REACHED",
"AUDIT_PAGE_LIMIT_EXCEEDED",
"AUDIT_ALREADY_RUNNING",
diff --git a/src/shared/error-codes.ts b/src/shared/error-codes.ts
index 5c3adc08..d72f88d6 100644
--- a/src/shared/error-codes.ts
+++ b/src/shared/error-codes.ts
@@ -11,6 +11,7 @@ const ERROR_CODES = [
"AUDIT_PAGE_LIMIT_EXCEEDED",
"AUDIT_ALREADY_RUNNING",
"VALIDATION_ERROR",
+ "UNKNOWN_LOCATION",
"CRAWL_TARGET_BLOCKED",
"BACKLINKS_BILLING_ISSUE",
"AI_SEARCH_BILLING_ISSUE",
@@ -34,6 +35,7 @@ const NON_REPORTABLE_ERROR_CODES = new Set<ErrorCode>([
"PAYMENT_REQUIRED",
"INSUFFICIENT_CREDITS",
"VALIDATION_ERROR",
+ "UNKNOWN_LOCATION",
"AUDIT_CAPACITY_REACHED",
"AUDIT_PAGE_LIMIT_EXCEEDED",
"AUDIT_ALREADY_RUNNING",
diff --git a/src/types/schemas/keywords.ts b/src/types/schemas/keywords.ts
index 1719bdaf..037f957f 100644
--- a/src/types/schemas/keywords.ts
+++ b/src/types/schemas/keywords.ts
@@ -20,6 +20,9 @@ export const researchKeywordsSchema = z.object({
keywords: z.array(z.string().min(1)).min(1).max(200),
locationCode: z.number().int().positive().optional(),
languageCode: z.string().min(2).max(8).optional(),
+ // Canonical DataForSEO name of a city, county, or region inside the
+ // country. Scopes volume, CPC, and competition to that area.
+ locationName: z.string().trim().min(1).max(200).optional(),
resultLimit: z
.union([z.literal(150), z.literal(300), z.literal(500)])
.default(150),
@@ -177,6 +180,8 @@ export const serpAnalysisSchema = z.object({
keyword: z.string().min(1),
locationCode: z.number().int().positive().optional(),
languageCode: z.string().min(2).max(8).optional(),
+ // Same area as the research it belongs to, for a local SERP.
+ locationName: z.string().trim().min(1).max(200).optional(),
// Only the two depths the app offers: the default top-20 snapshot, and the
// full 100 the SERP panel buys when a user pages past the loaded results.
// Each 10 of depth is another crawled Google page (~2.5 credits).
@@ -200,6 +205,7 @@ const keywordModes = ["auto", "related", "suggestions", "ideas"] as const;
export const keywordsSearchSchema = z.object({
q: z.string().optional(),
loc: z.coerce.number().int().positive().optional(),
+ locName: z.string().optional(),
kLimit: z.union([z.literal(150), z.literal(300), z.literal(500)]).optional(),
mode: z.enum(keywordModes).optional(),
cs: booleanSearchParamSchema.optional(),