First, ask whether you need Google at all
Most of my apps use free services without needing an API key and an account: Photon for address search, Open-Meteo for weather, OpenStreetMap through Overpass for gas stations and viewpoints and OSRM or BRouter for routes. I only need Google when there’s no free service that can do the job. There’s simply no free service (without needing an API key) for gas prices in the US, so Pump Fiction uses the fuelOptions field of Google’s Places API. This is the only field that needs a Google API key on this site.
My rule: use the free APIs as a base of the app and add Google API as an additional layer that can be switched on (when API key is present).
The short version: never ship the key to the browser
If you use Google API key on a website it becomes a public key. Anyone can see it in seconds (in the developer tools for example) and there are bots that search websites and code for it. If someone copies your key they could cause a big bill and use all your API quota (the restrictions will limit the damage, but won’t prevent it). The only safe way to use Google APIs is to keep the API key on your server and the website calls your server (see section 8). Sections 2 and 3 explain how the browser API key setup works (this site used to use that) because it’s good to understand what can go wrong with it.
1. Set up the project and the key
- Create a project in the Google Cloud console and add a billing account. Google Maps Platform won’t give you answers without it (even when you’re in the free usage).
- Enable the APIs that you use - this site uses Places API (New) and Pollen API. Note the “New”: the older Places API uses different URLs.
- Under APIs & Services → Credentials, create an API key. You can use a single API key with multiple APIs.
2. Why a browser key is not safe
A Google API key used from JavaScript is available to anyone (they just have to open the developer tools). You cannot hide it (it’s a static website) and ‘hiding’ it will only make it harder for you to debug. If someone gets your API key they can make the same API calls your web page makes as many times as they want (and Google bills you). If the API key isn’t restricted, they can also use it for all other APIs you’ve enabled. It’s worth keeping the API key out of git because bots will find it in a public repository within hours, but that doesn’t change the fact that all visitors to your website receive it.
This is how the site used to work and why I stopped it. Each app has a config.json in the repository with an empty Google API key.
{ "googleKey": "" }
The real API key is in a GitHub repository variable and the deployment workflow adds it just before uploading the site:
- name: Add the Google Maps key to the apps that use it
env:
GOOGLE_MAPS_KEY: ${{ vars.GOOGLE_MAPS_KEY }}
run: |
if [ -n "$GOOGLE_MAPS_KEY" ]; then
for app in pumpfiction goldenhour shouldiride; do
jq -n --arg k "$GOOGLE_MAPS_KEY" '{googleKey: $k}' > "$app/config.json"
done
fi
The web page reads it on startup and assumes that the Google API key is not available when the file is missing or the key is empty:
const config = fetch('config.json', { cache: 'no-store' })
.then((r) => (r.ok ? r.json() : {}))
.catch(() => ({}));
cache: 'no-store' is important: without it, browsers may keep using the old file after you update or rotate the API key. But this method keeps the API key out of git and then publishes it on the website (anyone can download the config.json file). That’s why the website no longer uses this method and section 8 explains what it switched to.
3. If a key must be public, restrict it twice
Restrictions don’t make a public API key safe. They just limit what a stolen API key can be used for. Set them on all your API keys (whether they’re in a web page or a server) and consider them damage control. In the API key settings you’ll see 2 different restrictions and you want both:
- Application restrictions → Websites
List the addresses where it can be used from (such as
https://www.dusanjov.com/*). Browsers on other websites will be refused, but anyone can add your address in a script and it’ll work. Addhttp://localhost:8000/*when you test locally and remove it afterwards (or have a separate API key for development). - API restrictions
Select only the APIs you enabled. If the API key gets copied anyway, it cannot be used for expensive APIs that you never use.
The check on the website is based on Referer field, which can be faked with a single line of curl command. So website restriction still allows anyone who copied your key to use it from anywhere. Only an API key that is on the server can use IP address restriction (see section 8), which is much more effective. Whatever you do, don’t forget to set the limit on usage from section 6 as your last line of defence.
4. Calling the Places API (New)
The newer version of Places API is a POST request with a JSON body. The API key is in a header along with a field mask that lists which fields you want to receive. If you don’t include a field mask the request will fail.
const res = await fetch('https://places.googleapis.com/v1/places:searchNearby', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Goog-Api-Key': key,
'X-Goog-FieldMask': 'places.id,places.displayName,places.location,places.fuelOptions',
},
body: JSON.stringify({
includedTypes: ['gas_station'],
maxResultCount: 20,
rankPreference: 'DISTANCE',
locationRestriction: {
circle: { center: { latitude: lat, longitude: lon }, radius: 10000 },
},
}),
});
You pay based on the field mask too: Google groups the fields in tiers and you pay for the most expensive field you request. Golden Hour only requests name, location and type and pays the least.
A few details I ran into:
- You get at most 20 results from each search and the search radius can be up to 50 km. For a longer drive, Pump Fiction splits the route into pieces of about 160 km and makes a
searchTextrequest withsearchAlongRouteParameters(the route as an encoded polyline) for each piece (at most 8). - Prices come as Google’s money type - whole
unitsas a string andnanos(billionths). You can useNumber(p.units) + p.nanos / 1e9to turn it into a regular number. - Place types change: over time they get more types and a request with an unknown type will fail with 400 error. Golden Hour will try once more with a shorter list of types that exist for longer.
- Google errors are readable -
error.messagein the response body. Displaying it to the user is better than “Something went wrong”, and “API key not valid” or “This API is not enabled” tell you exactly what to fix.
5. Calling the Pollen API
Not all Google APIs have the same interface - Pollen API is a regular GET request with the API key in the URL:
const url = 'https://pollen.googleapis.com/v1/forecast:lookup'
+ `?key=${encodeURIComponent(key)}`
+ `&location.latitude=${lat}&location.longitude=${lon}`
+ '&days=1&plantsDescription=false';
const r = await fetch(url);
if (!r.ok) return null; // e.g. a country with no pollen data
const day = (await r.json()).dailyInfo?.[0];
The data is available only in certain countries so a failed lookup isn’t a bug. Should I Ride? will use Open-Meteo’s numbers for pollen (only Europe) or skip pollen if neither has data.
6. Keep the bill at zero
Google Maps Platform has a free usage limit per month per API request type. The limit is smaller for more expensive request types. It’s hard to get that high usage on a personal website, but a bug that calls the API in a loop can do it. Three things I do to relax:
- Caching in the browser. Pollen only changes once a day, so Should I Ride? will cache the result of a lookup for 3 hours. Golden Hour will cache the spots it finds for a day for a given place and distance. Revisiting the web page is free. Google limits how long you can store their data (see their terms) so don’t cache these results for long.
- Capping the quota. You can set it under APIs & Services → [the API] → Quotas. Set ‘Requests per day’ to something you will never need. This will actually prevent requests (a budget alert will only email you). One problem: I couldn’t change these quotas while on the free trial (had to upgrade to paid).
- Set up a budget alert anyway (under Billing → Budgets & alerts) for a few dollars.
7. Make Google optional
All apps on this website work without the Google API key. Not just as a courtesy - it means that a revoked API key, a used up API quota or a Google outage will take out one feature, not all of it.
- Pump Fiction without a key shows gas stations from OpenStreetMap, but without prices.
- Golden Hour queries Google and OpenStreetMap at the same time, and if Google fails it shows the OpenStreetMap viewpoints and explains why.
- Should I Ride? will use Open-Meteo pollen data when it can or skip pollen.
const [google, osm] = await Promise.all([
googleKey ? googleSpots(googleKey, lat, lon, r).catch((e) => ({ error: e.message })) : [],
viewpoints(lat, lon, r).catch(() => []),
]);
Note that .catch on the Google API request - it’s important. Otherwise, the Promise.all will fail if the Google request rejects and take the free data with it.
8. The safe way: keep the key on your server
Everything I’ve explained so far is damage control for an API key that’s already public. The safe way is to not send the API key to the browser and instead the web page calls an address on your website (such as /api/stations) and your server adds the API key and forwards the request to Google. This is possible even if you have a static website (it’s probably served by a server) and doesn’t require a big framework. This site currently uses the Python version below for all 3 apps.
It changes your API key restriction too: instead of limiting it to your website, you limit it to your server’s IP address. That’s much more effective because your requests have to come from that IP address while Referer header can be easily faked by anyone (using curl).
The lightest option: nginx
If your site is already served by nginx, it can also do the forwarding without new software. It adds the API key and field mask and allows only a single endpoint and method used by the app:
# In the http block: at most 30 requests a minute per visitor
limit_req_zone $binary_remote_addr zone=google:1m rate=30r/m;
server {
# ...your existing site...
location = /api/places/searchNearby {
limit_except POST { deny all; }
limit_req zone=google burst=10 nodelay;
proxy_pass https://places.googleapis.com/v1/places:searchNearby;
proxy_ssl_server_name on;
include /etc/nginx/google-key.conf; # proxy_set_header X-Goog-Api-Key "...";
proxy_set_header X-Goog-FieldMask "places.id,places.displayName,places.location,places.fuelOptions";
proxy_set_header Cookie "";
}
}
The API key is in /etc/nginx/google-key.conf file outside of the web root and git repository, readable only by root. Setting the field mask in nginx means that a visitor can’t request more expensive fields and put them on your bill. Pollen API takes the API key in the URL, so in that case we use a rewrite to add it and nginx will append the query from the visitor (lat and lon) after it:
location = /api/pollen {
limit_except GET { deny all; }
limit_req zone=google burst=10 nodelay;
include /etc/nginx/google-pollen.conf; # rewrite ^ /v1/forecast:lookup?key=... break;
proxy_pass https://pollen.googleapis.com;
proxy_ssl_server_name on;
}
This is quick, but nginx is only a pipe - it can’t verify that a latitude is a latitude, it will just pass along the request body that the visitor sends and can’t use one answer to serve many people who ask the same question. For that you need a few lines of real code.
The safer option: a small Node or Python service
The whole point of moving the API key to a server is defeated if /api/ forwards any request it gets. You’ve created an open door to Google API with your key and anyone who finds the address will be able to use up your quota from a script. A small service solves that because the server decides what to ask and the visitor only provides the things that should change:
- Fixed endpoints.
/api/stationswill do one thing, there isn’t a generic “forward this to Google API” endpoint. - The server builds the request: place types, radius, number of results and field mask are set in code. The visitor only sends
latandlon(and they’re verified to be numbers in range). - A shared cache. Browser caching helps a single visitor. A cache on the server helps everyone (for example, 2 people in the same area will use 1 Google API call between them).
- A limit on the number of requests per visitor (so a script can’t use up the quota for the day).
- Plain errors - you return a short error message instead of Google API raw response.
Here it is in Node, without packages (Node 18 or higher has fetch built in):
// api.mjs: run with Node 18 or newer, no packages needed.
import http from 'node:http';
const KEY = process.env.GOOGLE_KEY; // from the environment, never from a file in the web root
const CACHE_MS = 30 * 60 * 1000;
const cache = new Map(); // shared by every visitor
const hits = new Map(); // requests per visitor this minute
setInterval(() => hits.clear(), 60 * 1000).unref(); // a new minute, a new count
setInterval(() => cache.clear(), 60 * 60 * 1000).unref(); // so the cache can't grow forever
function number(value, min, max) {
const n = Number(value);
if (value === null || !Number.isFinite(n) || n < min || n > max) throw new Error('bad input');
return n;
}
http.createServer(async (req, res) => {
const send = (code, body) => {
res.writeHead(code, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
};
const url = new URL(req.url, 'http://localhost');
if (req.method !== 'GET' || url.pathname !== '/api/stations') return send(404, { error: 'Not found' });
// nginx passes the visitor's address in X-Real-IP.
const ip = req.headers['x-real-ip'] || req.socket.remoteAddress;
hits.set(ip, (hits.get(ip) || 0) + 1);
if (hits.get(ip) > 20) return send(429, { error: 'Too many requests' });
let lat, lon;
try {
lat = number(url.searchParams.get('lat'), -90, 90);
lon = number(url.searchParams.get('lon'), -180, 180);
} catch {
return send(400, { error: 'lat and lon, please' });
}
// Round to about 1 km, so people near each other share one cached answer.
const where = `${lat.toFixed(2)},${lon.toFixed(2)}`;
const kept = cache.get(where);
if (kept && Date.now() - kept.at < CACHE_MS) return send(200, kept.data);
try {
const r = await fetch('https://places.googleapis.com/v1/places:searchNearby', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Goog-Api-Key': KEY,
// The server picks the fields, so nobody can ask for pricier ones on your bill.
'X-Goog-FieldMask': 'places.id,places.displayName,places.location,places.fuelOptions',
},
body: JSON.stringify({
includedTypes: ['gas_station'],
maxResultCount: 20,
rankPreference: 'DISTANCE',
locationRestriction: { circle: { center: { latitude: lat, longitude: lon }, radius: 10000 } },
}),
});
if (!r.ok) return send(502, { error: 'Google said no' });
const data = await r.json();
cache.set(where, { at: Date.now(), data });
send(200, data);
} catch {
send(502, { error: 'Google did not answer' });
}
}).listen(8787, '127.0.0.1'); // only nginx can reach it
Same in Python (using only standard library), here using Pollen API:
# api.py: Python 3, standard library only.
import json, os, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlencode, urlparse, parse_qs
KEY = os.environ['GOOGLE_KEY']
POLLEN = 'https://pollen.googleapis.com/v1/forecast:lookup'
cache = {} # pollen changes once a day, so keep answers for 3 hours
class Api(BaseHTTPRequestHandler):
def send(self, code, body):
data = json.dumps(body).encode()
self.send_response(code)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(data)
def do_GET(self):
url = urlparse(self.path)
if url.path != '/api/pollen':
return self.send(404, {'error': 'Not found'})
q = parse_qs(url.query)
try:
lat, lon = float(q['lat'][0]), float(q['lon'][0])
except (KeyError, ValueError):
return self.send(400, {'error': 'lat and lon, please'})
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
return self.send(400, {'error': 'lat and lon, please'})
where = f'{lat:.2f},{lon:.2f}'
kept = cache.get(where)
if kept and time.time() - kept[0] < 3 * 3600:
return self.send(200, kept[1])
params = urlencode({'key': KEY, 'location.latitude': lat, 'location.longitude': lon,
'days': 1, 'plantsDescription': 'false'})
try:
with urllib.request.urlopen(f'{POLLEN}?{params}', timeout=10) as r:
body = json.load(r)
except Exception:
return self.send(502, {'error': 'Google did not answer'})
cache[where] = (time.time(), body)
self.send(200, body)
ThreadingHTTPServer(('127.0.0.1', 8788), Api).serve_forever()
The service listens on 127.0.0.1 only so nobody from the internet can reach port 8787 (or 8788 in Python) directly. You can only reach it through nginx, which forwards the public /api/ address to the service, takes care of HTTPS and adds its own limit on the number of requests:
location /api/ {
limit_req zone=google burst=10 nodelay;
proxy_pass http://127.0.0.1:8787; # 8788 for the Python one
proxy_set_header X-Real-IP $remote_addr;
}
Now the page calls your own address (no key anywhere):
const r = await fetch(`/api/stations?lat=${lat}&lon=${lon}`);
const data = r.ok ? await r.json() : null; // no key anywhere in the page
To keep the service running if the machine reboots or the service crashes you can use a systemd unit. The API key is in an environment file only root can read and DynamicUser will run the service as a temporary user with no access to the rest of the system:
# /etc/systemd/system/site-api.service
[Unit]
Description=Small API for dusanjov.com
After=network-online.target
[Service]
ExecStart=/usr/bin/node /opt/site-api/api.mjs
EnvironmentFile=/etc/site-api/google.env # GOOGLE_KEY=..., chmod 600, owned by root
DynamicUser=yes
Restart=always
[Install]
WantedBy=multi-user.target
What’s still exposed
This applies to all 3 options. The service is private but keeping the API key private doesn’t make your /api/ private. It’s a public address and anyone can use it in the same way your web page does. You have control: they can’t copy the key and every request must pass your rules. A few more things to think about:
- Don’t add CORS headers. If your service doesn’t send
Access-Control-Allow-Originheader, other websites cannot use your/api/from their visitors’ browsers (scripts on a server can use it and that’s what rate limiting is for). - Verifying
OriginorRefereris a speed bump, not a lock. It’s ok to add it, but don’t rely on it. - Set the daily quota limit in Google Cloud - that’s still a limit that will work even if your code has a bug.
- Keep the key out of logs - Pollen API has the key in the URL so don’t log the full URLs that your service calls.
- It’s one more thing you have to run. A service needs updates and can stop working (that’s why the fallbacks from section 7 matter).
My rule: API key belongs on the server. Browser API key is only ok for a quick prototype or for an API designed to be used in the browser (like the map display in Maps JavaScript API) and even in that case it should be restricted with a quota cap. Anything that costs money per request should be behind a small service like the ones above.
9. How bigger services stop abuse
Public /api/ is the way most web apps work and they all have the question: how to stop someone from calling your /api/ a million times? No single trick will do that, so services use layers (from simplest to most complex):
- Rate limits per visitor - almost everyone starts with a limit such as 60 requests a minute per IP address (you can do this in nginx, the app or a CDN).
- Caching - the same question will have the same answer for a while and a flood of repeat requests won’t cost much on the paid API.
- A bot check - invisible challenge (such as Cloudflare Turnstile (which is free) or Google reCAPTCHA) runs on the web page and gives a token to a real browser. The API will only answer requests with a valid token (this stops most simple scripts).
- Short-lived signed tokens - the web page gets a token from the server (that expires in a few minutes) and the API refuses anything without a valid token. A request copied from the developer tools will stop working.
- A CDN or firewall in front - services like Cloudflare can block known bad bots and strange traffic before it reaches your server.
- Accounts - have to sign in before using, then each user has a quota. This is the strongest option and why most ‘serious’ APIs require a login, but overkill for free tools on a personal site.
- Monitoring and hard caps - you have alerts for usage, but you also have a daily cap that will stop.
For this site 1, 2 and 7 are sufficient and that’s what it uses: nginx and the Python service limit each visitor to 60 requests a minute, the service caches the answers for all visitors and it will stop after a set number of Google API calls a day (with Google’s quota cap behind that). If I start to see abuse in the logs, Turnstile is next. Until then, my apps remain free and don’t require signing up.
Things that will bite you
- “Places API” and “Places API (New)” are two different products. Enabling the old one doesn’t make the new URLs work.
- When you enable a new API you must do it twice - in the API library for your project and in the API restrictions of the API key. If you forget the second one you’ll get a 403 error that looks like the API key isn’t enabled.
- Changes to API keys and restrictions take a few minutes (5 minutes) to apply. Wait before you start debugging.
- Test on the real address. If your API key is restricted to a website, it won’t work from
file://pages or any other address you didn’t list. I found this when I had a preview website on a different domain. - When you restrict an API key to your server’s IP address, add both (if you have IPv6). My server has IPv6 and it usually uses it for communication with Google, so an API key that allowed only the IPv4 address would fail with a 403 error.
curl -4 ifconfig.meandcurl -6 ifconfig.mecan be used to find them. - It’s easy to rotate an API key (so do it the moment you suspect it leaked or if you ever paste it somewhere public) - create a new one, put it in the server’s key file, restart the service and delete the old API key.
Wrap-up
API key in the browser is a public key, and none of the restrictions will change that. Start with free APIs that don’t require a key and add Google only if they don’t have the data you need. Put the API key on the server (either with nginx or a small service that determines exactly what is requested from Google APIs) and restrict it to your server’s IP addresses and the APIs you use. Use a rate limit, a shared cache and a hard cap on daily usage in front of it, use as few fields as possible and don’t forget that the web page must work when Google stops answering.