An API key is a secret string that identifies and authenticates your application when it calls another service, like OpenAI, Stripe, or a database. Whoever holds the key can act as your application, which is why a leaked key is dangerous: it can run up charges, read data, or take actions in your name until it is revoked.
Public keys vs secret keys
Some keys are meant to be public, like a Supabase anon key or a Stripe publishable key, and are safe in client code as long as the service enforces its own permissions. Secret keys, like a Stripe secret key or a service_role key, grant real power and must only ever live on the server.
How to store a key safely
Keep secret keys in an environment variable, never hardcoded in source, and make sure the .env file is gitignored. Use them only in server-side code so they never ship to the browser. If a key is ever exposed, rotate it, because removing it from code does not undo the exposure.
Public keys vs secret keys
| Public key (publishable / anon) | Secret key (service_role / secret) | |
|---|---|---|
| Safe in the browser | Yes | Never |
| Examples | Stripe publishable, Supabase anon | Stripe secret, Supabase service_role |
| Where it belongs | Client or server code | Server only, from an env var |
| If it leaks | Usually fine, the service enforces limits | Rotate it immediately |
What this means for AI-generated code
AI coding tools frequently hardcode API keys inline because it is the shortest path to working code. A committed key is scraped from public repos within minutes, so the fix is to keep keys in environment variables and put a secret scanner in front of your commits.
Common questions
Where should I store my API keys?
Secret keys go in an environment variable that is only read by server-side code, with the .env file gitignored so it is never committed. Public keys can live in client code. Never write a secret key as a literal string in source.
What is the difference between a publishable and a secret key?
A publishable (or anon) key is meant to be public and safe in the browser because the service limits what it can do. A secret key grants full access and must stay server-side. Mixing them up, by shipping a secret key to the client, is a common high-severity flaw.
What should I do if my API key is exposed?
Rotate it right away: generate a new key in the service's dashboard and revoke the old one. Removing the key from your code does not undo the exposure, because it may already be in git history or have been scraped. Then store the new key in an environment variable.
Is it safe to use an API key in frontend code?
Only if it is a key the service explicitly marks as public or publishable. Any key that can move money, read private data, or bypass access rules must never appear in frontend code, because everything in the browser bundle is readable by every visitor.