Unit 7 · Data that lasts
Why API keys can’t go in front-end JavaScript
The browser downloads every line of front-end code, and anyone can read it in seconds. A secret key in that code is a public key. Keep it on your server, and have the page call your own API route instead.
The mix-up
What people often think
“A secret key is safe in the JavaScript because visitors never look at the code.”
What the tutor says
The browser downloads every line, and anyone can open it in seconds. Bots scan sites for keys all day. A secret key in front-end code is a public key.
Right-click any page and choose "View page source". What can you see?
How it works
Minifying only squashes code; it does not lock it. Encoding the key with something like btoa does not help either, because the page has to decode it to use it, so anyone can. Bots scan sites for keys all day, and a copied key can run up your bill.
The safe pattern: the page calls /api/... on your own server, and the server adds the key and calls the outside service. The same goes for database passwords: only the server talks to the database.
Side by side
fetch('https://api.example.com/v1/charge', {
headers: { Authorization: 'Bearer sk_live_...' },
});// browser
fetch('/api/charge', { method: 'POST', body: JSON.stringify(order) });
// the server adds the key and calls the providerClose cousins of this mix-up
The tutor watches for these in the same lesson.
“An API key is fine in the browser if the code is minified.”
Minified code is just squashed, not locked. Someone who copies the key can run up your bill. Call your own server, and let it use the key.
“Scrambling the key, like encoding it with btoa, hides it.”
The page has to unscramble it to use it, so anyone can too. The only safe place for a secret key is the server.
“The page should call the outside service directly.”
Calling an outside service needs its key, and the page cannot hold a key safely. Call your own /api/ route, and let the server make the outside call.
“The page needs the database password to load data.”
The page asks your server for data, and only the server talks to the database. Anyone with the password could read or delete everything.
Practise it with a tutor watching
APIs and auth basics
Keep secret keys on the server and explain how a site knows who you are after you log in.
Free, no account needed.