Keep API keys secret

A key in a repository or a browser bundle is a published key. Keep it in the environment, put a small proxy between the browser and the API, and know exactly what to do the day one leaks.

An API key is a bearer credential: whoever holds it can use it, and there is no second factor on an API call. On APIVerve, holding your key means spending your credits. That makes key handling most of your security posture, and the failures are boringly predictable. Keys end up in three places they should not: in source control, in browser code, and in logs.

This lesson closes each of those, in that order, and then covers the part people skip until it is too late: what to do when one gets out anyway.

Keys live in the environment

You have been doing this since lesson one: the code reads APIVERVE_API_KEY from the environment and fails at startup if it is missing. The point of an environment variable is that the value is supplied by wherever the code runs (your shell, a CI system, a hosting platform's settings page), not by the code itself. The same file runs in development and production with different keys and contains neither.

const KEY = process.env.APIVERVE_API_KEY;
if (!KEY) throw new Error('APIVERVE_API_KEY is not set');
import os
KEY = os.environ["APIVERVE_API_KEY"]  # KeyError at startup if unset

Typing export in every new terminal gets old, so most projects keep development values in a .env file and load it at startup.

.env
APIVERVE_API_KEY=YOUR_API_KEY
// npm install dotenv
import 'dotenv/config';            // loads .env into process.env
console.log(Boolean(process.env.APIVERVE_API_KEY));

// Node 20.6+ can skip the package: node --env-file=.env app.mjs

.gitignore before the first commit

A .env file is only safe if it never enters version control. Add it to .gitignore before your first commit, not after you notice it in git status:

.gitignore
.env
.env.*
!.env.example
.dev.vars

Commit a .env.example with the variable names and placeholder values instead, so the next person knows what to set.

Order matters because git history is permanent. If .env was committed once and deleted in the next commit, the key is still in the repository, in every clone, and in every fork. Rewriting history is possible but does not reach copies that already exist. Treat a committed key as a leaked key, even in a private repository: private repositories get shared, made public, cloned onto laptops, and read by every integration you have connected.

Check yourself

You committed .env with your key, noticed, and deleted it in the next commit. The repository is private. What is the situation?

Answer the check above to continue.

Run every example on your own key. Free plan, no card.

Scaling up?

Volume pricing, custom SLAs, and dedicated support for high-traffic teams.

Contact sales