






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







~/app $ cat .env # API_KEY=sk_live_????????????????
Hiding environment variables & API keys in HTML/JS apps Web Development · Frontend Security Fundamentals
0 1 · T H E P R O B L E M
If it reaches the client, it is not a secret. There is no obfuscation, minification, or trick that hides a key from someone with DevTools open.
0 3 · M Y T H - B U S T I N G
VITE_API_KEY=abc123secret // main.js const k = import.meta.env.VITE_API_KEY;
// dist/bundle.js (public!) const k= "abc123secret" ; // value is baked into the // file every visitor downloads What .env is actually for in frontend tooling
0 4 · T H E G O L D E N R U L E
Golden rule: secret keys live only on a server you control. The browser gets, at most, public keys. OK in the browser (public)
0 5 · S O L U T I O N 1 — C O D E
// server.js (runs on YOUR server) import express from "express"; import "dotenv/config"; // loads .env const app = express(); app.get("/api/data", async (req, res) => { const r = await fetch("https://api.example.com", { headers: { Authorization: Bearer ${process.env.API_KEY} } }); res.json(await r.json()); }); app.listen( 3000 ); // frontend app.js (public) const data = await fetch( "/api/data" ).then(r => r.json()); // no key anywhere ✓ The secret stays in .env on the server process.env is real here — Node reads it at runtime from the machine, not from a shipped bundle.
0 6 · S O L U T I O N 2
Static-site hosts can run tiny backend functions for you — perfect for HTML/JS apps with one or two secret calls. // netlify/functions/data.js export default async (req) => { const r = await fetch(URL, { headers: { Authorization: Bearer ${process.env.API_KEY} } }); return Response.json(await r.json()); }; Where to set the key
0 8 · R E C A P
Never ship secrets to the browser No secret keys in HTML, JS, or frontend .env builds. Proxy through a backend Express route or serverless function attaches the key server-side. Ignore .env, commit .env.example Keep real values out of git; document variable names. Restrict public keys Lock browser keys to your domain / specific APIs in the provider dashboard. Rotate on any leak Assume a committed or shipped key is compromised — revoke and reissue. Use host env settings in prod Set variables in Netlify / Vercel / your server, never in the code. If the browser can read it, so can everyone else. Keep secrets on the server.