Where to keep the API key in a site built with AI
Short answer: on the server, in an environment variable. The browser calls an address on your site, and the server adds the key and calls the API.
browser -> /api/contact on your site -> the API (with the key)Why not in the browser
Section titled “Why not in the browser”Everything that reaches the browser can be read: code, variables, network requests. Minification hides nothing. A key read from the page can be used by anyone, with all its permissions.
Mistakes generated code often makes
Section titled “Mistakes generated code often makes”- the key written straight into a component, “just to make it work”;
- the key in
PUBLIC_,NEXT_PUBLIC_orVITE_, which all end up in the browser; - the
.envfile pushed to git; - a proxy route that forwards any path it receives;
- the key printed in logs or in an error message.
What it looks like done right, in Astro
Section titled “What it looks like done right, in Astro”// src/pages/api/contact.ts (runs on the server)export const prerender = false
export async function POST({ request, clientAddress }) { const { name, email, message, website } = await request.json()
const res = await fetch(`${import.meta.env.RIVIL_URL}/api/site/v1/forms/contact`, { method: 'POST', headers: { Authorization: `Bearer ${import.meta.env.RIVIL_SITE_KEY}`, 'Content-Type': 'application/json', 'X-Rivil-Client-IP': clientAddress, }, body: JSON.stringify({ name, email, message, website }), })
return new Response(null, { status: res.ok ? 202 : 502 })}The same in Next (Route Handler or Server Action), Nuxt (server/api) and SvelteKit (+server.ts). Add a rate limit on your route too.
How to check
Section titled “How to check”- Open the site, then developer tools, the Network tab.
- Submit the form. The request must go to your domain, with no
Authorizationheader carrying the key. - Search the built files (
dist,.next) for the first characters of the key. It must not appear in anything sent to the browser. - Check that
.envis in.gitignore.
If you found it, revoke it and create another. See backend security.
Frequently asked
Section titled “Frequently asked”Can I keep the key in an environment variable and use it in the browser?
No. A variable used in browser code ends up in the files sent to the visitor. An environment variable is safe only when server code reads it.
I have a static site. What do I do?
Add a server function or a small service that holds the key. In Astro it is enough to enable server routes for the pages that send data.
I pushed the key to GitHub. What now?
Revoke it immediately and create another. Deleting it from the code is not enough, because it stays in history and may already be copied.