← Back to dashboard
geolocationtoolingfreshReader view (for NotebookLM)

Geolocation Integration Guide

What is the Geolocation API?

The real model

Consent-gated device location (GPS/Wi-Fi/cell), foreground-only, HTTPS-only — with IP as the coarse silent fallback.

Two callbacks (success → GeolocationPosition, error → code 1/2/3 for denied/unavailable/timeout). watchPosition keeps the radio warm, so clearWatch in your React effect cleanup is mandatory or you leak battery. There is no background location and no native geofence on the web — you approximate geofencing with haversine distance on each foreground update. Crucially for codeAmani: a stored lat/lng accurate to ~1,750–1,850 ft is 'precise geolocation' — sensitive personal information under CCPA, consent-only and never-for-sale under Virginia and Oregon law (KDPA 2019 on Kenya-targeted projects). Default from edge IP geo, ask for the precise fix only when a feature needs it, round before storing.

Seven location primitives

From one-shot fixes to live tracking — and the privacy rules that bind them.

Text
 ██████╗ ███████╗ ██████╗ ██╗      ██████╗  ██████╗ █████╗ ████████╗██╗ ██████╗ ███╗   ██╗
██╔════╝ ██╔════╝██╔═══██╗██║     ██╔═══██╗██╔════╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
██║  ███╗█████╗  ██║   ██║██║     ██║   ██║██║     ███████║   ██║   ██║██║   ██║██╔██╗ ██║
██║   ██║██╔══╝  ██║   ██║██║     ██║   ██║██║     ██╔══██║   ██║   ██║██║   ██║██║╚██╗██║
╚██████╔╝███████╗╚██████╔╝███████╗╚██████╔╝╚██████╗██║  ██║   ██║   ██║╚██████╔╝██║ ╚████║
 ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Geolocation Integration Guide

Focus: know where a user is with the least precision the feature needs — default from the request IP at the edge, ask the browser for a GPS fix only with explicit, revocable consent, turn coordinates into addresses server-side, and treat every stored lat/lng as sensitive personal data under US state privacy law (and KDPA 2019 on Kenya-targeted projects).

Overview

There are three sources of "where", at opposite ends of the precision/consent spectrum:

SourceHowPrecisionConsentCost
Device (navigator.geolocation)GPS / Wi-Fi / cell, in the browsermetresBrowser prompt, HTTPS only, revocableFree; battery
Edge IP geoVercel geolocation(request) / x-vercel-ip-*; Cloudflare request.cfcity (often wrong on mobile/VPN)None (but the IP is still personal data)Free, zero extra calls
Geocoding / Places providerGoogle Maps Platform, Mapbox, Nominatim — server-sideaddress ↔ pointn/a (you send it data you already hold)Per-request, per-SKU

A good product renders immediately from the IP default, asks for the precise signal from a user gesture only when the feature needs it (map pin, nearest store, live delivery), and degrades gracefully when permission is denied.

Hard truths that shape every integration:

  • Consent is mandatory and revocable. The first getCurrentPosition/watchPosition call triggers the browser prompt. Users can deny, or grant then revoke in site settings. Handle granted / denied / prompt, and the Permissions change event mid-session.
  • Secure context only. navigator.geolocation works only over HTTPS (localhost counts). Cross-origin iframes also need allow="geolocation" — the geolocation Permissions-Policy default allowlist is self.
  • Foreground only. The web API has no background location and no native geofence. Updates stop when the tab is hidden.
  • A watchPosition you don't clear is a battery leak. clearWatch in the React effect cleanup — non-negotiable.
  • Precise location is sensitive data in the US. See Privacy & compliance.

Official Documentation

SourceURLWhat it covers
MDN Geolocation APIhttps://developer.mozilla.org/en-US/docs/Web/API/Geolocation_APIgetCurrentPosition, PositionOptions, errors, secure context, Permissions-Policy
MDN watchPositionhttps://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPositionWatcher signature, clearWatch
MDN Permissions APIhttps://developer.mozilla.org/en-US/docs/Web/API/Permissions_APInavigator.permissions.query, change event
MDN <geolocation> elementhttps://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/geolocationExperimental declarative permission control (Chrome 144+)
W3C Geolocation spechttps://www.w3.org/TR/geolocation/Normative model, privacy requirements
@vercel/functions referencehttps://vercel.com/docs/functions/functions-api-reference/vercel-functions-packagegeolocation(), ipAddress()
Vercel request headershttps://vercel.com/docs/headers/request-headersx-vercel-ip-country, -country-region, -city, -latitude, -longitude, -timezone, -continent, -postal-code
Cloudflare Request (request.cf)https://developers.cloudflare.com/workers/runtime-apis/request/IncomingRequestCfProperties geo fields
Google Geocoding API v4https://developers.google.com/maps/documentation/geocoding/geocoding-v4-overviewForward / reverse / place geocoding, destinations
Google Places API (New)https://developers.google.com/maps/documentation/places/web-service/nearby-searchNearby / Text Search, Autocomplete, field masks
Google Maps Platform pricinghttps://developers.google.com/maps/billing-and-pricing/pricingPer-SKU free caps (since 2025-03-01)
Mapbox Geocoding v6https://docs.mapbox.com/api/search/geocoding/Forward / reverse, temporary vs permanent
Nominatim usage policyhttps://operations.osmfoundation.org/policies/nominatim/Public OSM geocoder rules (1 req/s, forbidden uses)

Versions & prices (verified 2026-10-20)

ItemValue
@vercel/functions3.10.1
@cloudflare/workers-types5.20261019.1 (or generate with wrangler types)
next16.4.2 (middleware.ts is now proxy.ts)
Google Geocoding (Essentials)10,000 free / month, then $5.00 / 1,000
Google Places Nearby Search Pro / Text Search Pro5,000 free / month, then $32.00 / 1,000
Google Place Details Essentials / Pro10,000 / 5,000 free, then $5.00 / $17.00 per 1,000
Google Autocomplete Requests10,000 free, then $2.83 / 1,000 (Session Usage: unlimited free)
Google Dynamic Maps / Static Maps10,000 free, then $7.00 / $2.00 per 1,000
Mapbox Temporary Geocoding100,000 free / month, then $0.75 / 1,000
Mapbox Permanent Geocodingno free tier, $5.00 / 1,000 (1–500k)
Mapbox Map Loads (GL JS)50,000 free, then $5.00 / 1,000
Nominatim (public OSM server)free, max 1 req/s, strict usage policy

The shape of a position

A success callback receives a GeolocationPosition: a coords object plus a timestamp (epoch ms).

coords fieldMeaningNotes
latitude / longitudeWGS84 decimal degrees (numbers)The PII. Treat as sensitive.
accuracyRadius of confidence, metresAlways present. ~5–20 m with GPS, hundreds with Wi-Fi.
altitude / altitudeAccuracyMetresnull on most phones.
headingDegrees from true northnull when stationary.
speedm/snull unless moving.
Error codeConstantYour move
1PERMISSION_DENIEDFall back to IP / manual entry. The browser won't re-prompt.
2POSITION_UNAVAILABLERetry or fall back.
3TIMEOUTRetry with a longer timeout.
TypeScript
interface PositionOptions {
  enableHighAccuracy?: boolean; // default false — true asks for GPS (slower, more battery)
  timeout?: number;             // default Infinity (ms) — max wait for a fix
  maximumAge?: number;          // default 0 (ms) — accept a cached fix up to this old
}

Pattern 1 — check permission, then getCurrentPosition

Query the Permissions API first so you can tailor the UX; trigger the prompt from a user gesture after explaining why.

TypeScript
// lib/geolocation.ts — full version in examples/browser-geo.ts
export type GeoState = "granted" | "denied" | "prompt" | "unsupported";

export async function getGeoPermission(): Promise<GeoState> {
  if (typeof navigator === "undefined" || !("geolocation" in navigator)) return "unsupported";
  if (!("permissions" in navigator)) return "prompt";
  try {
    const status = await navigator.permissions.query({ name: "geolocation" });
    return status.state; // "granted" | "denied" | "prompt"
  } catch {
    return "prompt";
  }
}

export function getCurrentPosition(
  options: PositionOptions = { enableHighAccuracy: true, timeout: 10_000, maximumAge: 60_000 },
): Promise<GeolocationPosition> {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, options);
  });
}

Progressive enhancement: the <geolocation> element (experimental)

MDN now documents a declarative <geolocation> HTML element (HTMLGeolocationElement) that renders a browser-controlled "use location" button with a consistent permission UI. It is experimental, not Baseline — Chrome / Chrome Android 144+ only. Attributes include autolocate and watch; read element.position / element.error in its location event. Feature-detect with typeof HTMLGeolocationElement === "function" and keep the navigator.geolocation path as the fallback (put the fallback button inside the element). Don't build a product flow that depends on it yet.

iframes

The geolocation Permissions-Policy directive defaults to self. An embedded third-party map/widget needs <iframe src="…" allow="geolocation"> (and your Permissions-Policy header must not block it).


Pattern 2 — watchPosition with React cleanup

watchPosition fires on position change and returns an id you must pass to clearWatch.

TSX
"use client";
import { useEffect, useState } from "react";

type Fix = { lat: number; lng: number; accuracy: number; at: number };

export function useWatchPosition(active: boolean) {
  const [fix, setFix] = useState<Fix | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!active || typeof navigator === "undefined" || !("geolocation" in navigator)) return;

    const watchId = navigator.geolocation.watchPosition(
      (pos) => {
        const c = pos.coords;
        setFix({ lat: c.latitude, lng: c.longitude, accuracy: c.accuracy, at: pos.timestamp });
        setError(null);
      },
      (err) => setError(`(${err.code}) ${err.message}`),
      { enableHighAccuracy: true, timeout: 15_000, maximumAge: 5_000 },
    );

    return () => navigator.geolocation.clearWatch(watchId); // release the GPS radio
  }, [active]);

  return { fix, error };
}

Foreground only. Once the tab is backgrounded or closed, updates stop. For genuine background tracking you need a native app (or the WhatsApp "share live location" feature on Kenya-targeted projects); design ops flows around periodic foreground check-ins.

Accuracy & battery trade-offs

GoalenableHighAccuracymaximumAgeSourceCost
Rough default (store finder centre)falselarge (5 min)Wi-Fi/cell/cachecheap
One-off pin on a maptrue0GPSone GPS wake
Live route trackingtruesmall (5 s)GPS continuousbattery-heavy

Request high accuracy only when the UI plots a precise point; stop watchers the moment the screen isn't visible; gate continuous tracking behind an explicit "I'm on a delivery" state.

Geofencing (foreground)

No native web geofence. Keep a target point + radius and compute haversine distance on each watchPosition tick:

TypeScript
export function distanceMeters(a: [number, number], b: [number, number]): number {
  const R = 6_371_000;
  const toRad = (d: number) => (d * Math.PI) / 180;
  const dLat = toRad(b[0] - a[0]);
  const dLng = toRad(b[1] - a[1]);
  const h =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}
// inside watchPosition success: if (distanceMeters(here, dropoff) < 50) markArrived();

Server-side / background geofencing: push points to the backend and evaluate there (PostGIS ST_DWithin(geog, ST_MakePoint(lng, lat)::geography, meters)). Note PostGIS and GeoJSON order is lng, lat.


Vercel — geolocation(request) from @vercel/functions

geolocation() just reads the x-vercel-ip-* headers Vercel's proxy injects, so it works in any Vercel Function runtime (Node.js default or Edge), in route handlers, and in the Next.js 16 proxy.ts. NextRequest.geo / NextRequest.ip were removed in Next.js 15.

TypeScript
// app/api/geo/route.ts — full version in examples/edge-geo.ts
import { geolocation } from "@vercel/functions";

export function GET(request: Request) {
  const geo = geolocation(request);
  return Response.json({
    country: geo.country ?? "US",            // ISO 3166-1 alpha-2
    countryRegion: geo.countryRegion ?? null, // e.g. "FL" — the user's state
    city: geo.city ? decodeURIComponent(geo.city) : null,
    timezone: request.headers.get("x-vercel-ip-timezone"), // not in geolocation()
    source: "ip",
    precise: false,
  });
}

Gotchas (verified against the package's Geo type, v3.10.1):

  • latitude / longitude are strings — Number.parseFloat before maths. They're a city centroid, never "the user's location".
  • geo.region is the Vercel edge region ("iad1"), not the user's state — use countryRegion.
  • x-vercel-ip-city is RFC 3986-encoded for non-ASCII names — decodeURIComponent.
  • x-vercel-ip-timezone and x-vercel-ip-continent exist as headers but aren't returned by geolocation().
  • Everything is undefined under next dev — always default.

Next.js 16: the middleware file convention is deprecated and renamed proxy (export function proxy(request), default runtime Node.js). See examples/proxy.ts.

Cloudflare Workers — request.cf

TypeScript
// full version in examples/cloudflare-geo.ts
export default {
  async fetch(request: Request): Promise<Response> {
    const cf = request.cf as IncomingRequestCfProperties | undefined;
    const country = cf?.country ?? request.headers.get("CF-IPCountry") ?? "US";
    return Response.json({ country, regionCode: cf?.regionCode ?? null, city: cf?.city ?? null });
  },
} satisfies ExportedHandler;

request.cf geo fields: country, city, continent, region (name, e.g. "Texas"), regionCode ("TX"), postalCode, metroCode, latitude/longitude (strings), timezone, isEUCountry, plus colo (data centre) and asn. Not populated in the dashboard/Playground preview.

Accuracy ceiling: city, and often wrong. Mobile carrier NAT (very common in Kenya, common on US carriers too) and VPNs skew results by city or country. Use IP geo to default a locale/currency/store, never for access control, fraud decisions, or tax.


Geocoding & places (server-side only)

Coordinates mean nothing to a customer; addresses do. Geocoding is always a server-side call so the key never ships to the browser. (A Maps JavaScript API key in the browser is normal, but it must be a separate key restricted by HTTP referrer and to the Maps JS API only.)

Google Maps Platform

  • Billing model (since 2025-03-01): the flat $200/month credit is gone; each SKU has its own monthly free usage cap — Essentials 10,000, Pro 5,000 (some "IDs only" SKUs unlimited). See the pricing table above.
  • Geocoding API v4 is GA at geocode.googleapis.com/v4/... (v3 maps.googleapis.com/maps/api/geocode/json still works and is not on the Legacy list). v4 renames fields to camelCase: results[].formattedAddress, location.latitude/longitude, granularity (was location_type), addressComponents[].longText; language→languageCode, region→regionCode (no default in v4 — v3 defaulted to us). Errors use HTTP status codes, not status strings. Pass X-Goog-Api-Key and a X-Goog-FieldMask.
    • Forward: GET https://geocode.googleapis.com/v4/geocode/address/{URL-encoded address}
    • Reverse: GET https://geocode.googleapis.com/v4/geocode/location/{lat},{lng}
    • granularity values: ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE — treat the last two as low confidence and ask for a pin.
    • Google warns not to call v4 directly from client-side JavaScript (key abuse risk). Default quota 25 QPS.
  • Places API (legacy) is Legacy as of 2025-03-01 and cannot be enabled in new Cloud projects. Use Places API (New): POST https://places.googleapis.com/v1/places:searchNearby / places:searchText / places:autocomplete. X-Goog-FieldMask is required and decides the billed SKU (asking for places.displayName makes it a Pro call). Nearby maxResultCount ≤ 20. Directions/Distance Matrix are likewise Legacy → use the Routes API.
TypeScript
// Reverse geocode (v4) — full helpers incl. Places Nearby + Mapbox fallback in examples/geocode-server.ts
const res = await fetch(`https://geocode.googleapis.com/v4/geocode/location/${lat},${lng}`, {
  headers: {
    "X-Goog-Api-Key": process.env.GOOGLE_MAPS_API_KEY ?? "",
    "X-Goog-FieldMask": "results.formattedAddress,results.location,results.granularity,results.placeId",
  },
});
const { results = [] } = (await res.json()) as {
  results?: Array<{ formattedAddress?: string; granularity?: string }>;
};
const address = results[0]?.formattedAddress ?? null;

Google's Maps Platform terms restrict caching/storing most returned content — read the service-specific terms before persisting addresses or coordinates that came from Google (persisting the coordinates the user gave you, e.g. a pin, is your own data).

Mapbox Geocoding v6

  • Forward GET https://api.mapbox.com/search/geocode/v6/forward?q=…&access_token=…; reverse …/v6/reverse?longitude=…&latitude=…&access_token=…. GeoJSON features, coordinates in [lng, lat] order. Rate limit 1,000 req/min.
  • Temporary results (default) may not be cached or stored; add permanent=true to store them — billed as Permanent Geocoding ($5.00/1,000, no free tier) vs Temporary (100k free, then $0.75/1,000).
  • v5 (/geocoding/v5/mapbox.places) is documented as the "previous version"; build new code on v6.

Nominatim (OpenStreetMap)

The public server (nominatim.openstreetmap.org) is donated capacity with a strict policy: max 1 request/second per application, a real identifying User-Agent/Referer, visible OSM attribution (ODbL), cache results, and be able to switch providers without an app update. Forbidden: client-side autocomplete, systematic/grid reverse queries, and using it as the geocoder for package/vehicle-tracking apps or reselling results. That rules it out for delivery/dispatch products (e.g. boda dispatch) and for production autocomplete. Use it only for low-volume, user-triggered lookups in internal tools — or self-host Nominatim / use a commercial OSM-based provider.

Provider choice

NeedDefault pick
US address search / autocomplete in a productGoogle Places API (New) Autocomplete + session tokens, or Mapbox Search Box
Reverse-geocode a pin for displayGoogle Geocoding v4 (10k free) → Mapbox Temporary (100k free) fallback
Store geocoded results permanentlyMapbox Permanent Geocoding, or Google with terms check
"Nearest X" over your own locationsPostGIS / haversine in your DB — no Places call at all
Internal/low-volume toolingNominatim (within policy)

Kenya addressing & pin-drop (Kenya-targeted projects only)

Most Kenyan deliveries have no usable street address — people give landmarks ("opposite Naivas, blue gate"). So for Kenya-targeted products:

  • Pin-primary. On WhatsApp flows, ask the customer to share a location pin (WhatsApp location message) — that's GPS-quality and needs no browser permission. Free text is the fallback, geocoded with regionCode=KE (v4) / components=country:KE (v3) and region bias.
  • Confidence gate. A geocode with granularity GEOMETRIC_CENTER/APPROXIMATE (v3 location_type or partial_match) is low-confidence: never auto-dispatch a pickup from it — nudge for a pin; let a low-confidence drop-off proceed but flag needs_review. Clamp absurd distances (e.g. > 50 km in a city) as geocode errors. (This is the boda-dispatch spec's policy; if that code moves to Geocoding v4, map location_type → granularity.)
  • Reverse-geocode pins so riders/operators see a human label, and keep the customer's landmark text alongside it.
  • Plus Codes (plusCode.globalCode in Google responses) are a shareable fallback "address" where no street address exists.
  • Never use the public Nominatim server for dispatch — its policy bans vehicle/package-tracking use.
  • 2G/3G and budget Android: lazy-load any map SDK, prefer a Static Maps image or no map at all on WhatsApp-first flows, and keep live tracking short.

Privacy & compliance

Engineering guidance, not legal advice — confirm with counsel before launching location features.

United States (default)

LawWhat it says about locationEngineering consequence
California CCPA/CPRA (Civ. Code §1798.140)"Precise geolocation" = device data locating a consumer within a circle of 1,850 ft radius; it is sensitive personal informationDisclose it at collection; honour the "Limit the Use of My Sensitive Personal Information" right — use it only for the service the user asked for
Virginia CDPA (§59.1-575, -578)"Precise geolocation data" = within 1,750 ft; sensitive data → opt-in consent to process; controllers must not sell or offer for sale precise geolocation dataExplicit consent before collecting; no selling/sharing for consideration, ever
Oregon OCPA (HB 2008)Sale of precise geolocation (1,750 ft, past or present) banned since 2026-01-01, for all consumersSame: never sell; check every analytics/ads SDK that might receive it
Other state comprehensive privacy laws (Colorado, Connecticut, Texas, Maryland, …)Commonly list precise geolocation as sensitive data needing consent; Maryland's MODPA is stricter still (not re-verified in the 2026-10-20 refresh — check each statute)Design to the strictest: consent, minimisation, no sale
FTC Act §5The FTC has pursued unfair-practice cases over selling/sharing sensitive location data (not re-verified this refresh)Don't pass raw location to ad/data-broker SDKs

Design rules that satisfy all of the above:

  • Consent before collection, with a plain-language rationale shown before the browser prompt; record the consent (timestamp, purpose, version).
  • Minimise precision. Round to the coarsest value the feature needs before storing — 2 decimals ≈ 1.1 km (below the "precise" threshold), 3 ≈ 110 m, 4 ≈ 11 m. Store the result (nearest store id) rather than the raw trail when you can.
  • Purpose limitation & no sale/sharing. Never forward lat/lng to analytics, ad pixels, or LLM prompts unless that's the stated purpose. Strip it from Sentry events/breadcrumbs and logs.
  • Retention. Short TTL for location history (e.g. delete delivery trails 30–90 days after completion); support access/deletion requests.
  • Security. Encrypt at rest, Supabase RLS / Neon role scoping so users read only their own rows, no location in URLs or client bundles.
  • Revocation is real. Listen for the Permissions change event; stop tracking and persistence immediately on denied. Once denied, the browser won't re-prompt — never nag.
  • IP addresses and IP-derived geo are personal data too under most privacy regimes. Don't log them alongside user ids.

Kenya-targeted projects — KDPA 2019

Location is personal data under Kenya's Data Protection Act, 2019. Same playbook: lawful basis (usually consent — freely given, specific, informed, revocable), purpose limitation, minimisation, defined retention, data-subject rights (access, correction, erasure), and registration with the ODPC where required. See COMPLIANCE_GUIDE.md.


Environment variables

Secrets (store via the secrets vault / Vercel env, never NEXT_PUBLIC_*):

Bash
GOOGLE_MAPS_API_KEY=AIza...server-restricted
MAPBOX_ACCESS_TOKEN=pk.eyJ...server-side-token

Non-secret settings:

SettingExampleNotes
NEXT_PUBLIC_GOOGLE_MAPS_BROWSER_KEYAIza…Separate key, HTTP-referrer-restricted to your domains and to Maps JavaScript API only. Public by design.
NEXT_PUBLIC_MAPBOX_PUBLIC_TOKENpk.eyJ…Mapbox public (pk.) token with URL restrictions, for GL JS map tiles only.
GEO_DEFAULT_COUNTRYUS (or KE on Kenya-targeted projects)Fallback when IP geo is missing.
NOMINATIM_USER_AGENTcodeamani-internal-tool/1.0 (ops@…)Required identifying UA if you use the public Nominatim server.

Never put the server-side key/token (GOOGLE_MAPS_API_KEY, MAPBOX_ACCESS_TOKEN) in client code.


codeAmani notes

  • US-first default. Edge IP geo (geolocation(request)) seeds country/state/currency/nearest-store on first render with country ?? "US"; the precise browser fix is opt-in, triggered from a button, for features that truly need it.
  • Store finder / "near me". One-shot getCurrentPosition on tap → server query over our own locations (PostGIS ST_DWithin or haversine) → no Places API call needed. Only call Places (New) when searching Google's POI data, with the tightest field mask.
  • Precise location is sensitive data. Consent record + rationale before the prompt, round before storing, short retention, never sold/shared, never in logs, analytics, Sentry, or LLM prompts (Claude/OpenAI routing included — send the derived result, e.g. "Nairobi CBD", not coordinates, unless the feature requires it).
  • Keys server-side. GOOGLE_MAPS_API_KEY / MAPBOX_ACCESS_TOKEN live in the vault / Vercel env and are used only from route handlers or server actions (import "server-only"). The browser gets a separate referrer-restricted key.
  • Budget the free caps. Google Geocoding 10k/month and Places Pro 5k/month go fast — cache what the terms allow, debounce autocomplete with session tokens, set daily quotas in Cloud Console, and put Sentry alerts on 429/403 responses.
  • Payments are unrelated to location. Don't gate Stripe (default rail) on IP country; for Kenya-targeted projects, M-Pesa availability is decided by the project, not by geo-IP.
  • Kenya-targeted projects: pin-primary capture via WhatsApp location messages, Google geocode fallback with regionCode=KE and a confidence gate, Plus Codes as the address fallback, KDPA consent, render times in Africa/Nairobi (EAT, UTC+3) while storing UTC, and design for 2G/3G + budget Android (no always-on high-accuracy watchers).
  • HTTPS everywhere. navigator.geolocation needs a secure context — fine on Vercel/Cloudflare and localhost; never on a plain-HTTP preview or LAN IP.