Skip to content

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)

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.

  • the key written straight into a component, “just to make it work”;
  • the key in PUBLIC_, NEXT_PUBLIC_ or VITE_, which all end up in the browser;
  • the .env file pushed to git;
  • a proxy route that forwards any path it receives;
  • the key printed in logs or in an error message.
// 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.

  1. Open the site, then developer tools, the Network tab.
  2. Submit the form. The request must go to your domain, with no Authorization header carrying the key.
  3. Search the built files (dist, .next) for the first characters of the key. It must not appear in anything sent to the browser.
  4. Check that .env is in .gitignore.

If you found it, revoke it and create another. See backend security.

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.