← Tutorials
SETUP · SECURITY · 5 MIN

Your first API key, without leaking it

You pasted the API key straight into the code, pushed the project to GitHub, and half an hour later your balance is zero. It's not bad luck. There are bots crawling public repos looking for keys exactly like that. Here's the right way.

For
anyone starting to use APIs (Anthropic, OpenAI, etc.) in their projects
Needs
a project with git and a terminal
Time
5 minutes

An API key is like the password to your account on a service: whoever has it can spend your money. The classic mistake is writing it inside the code, like this:

# BAD. Never do this.
const apiKey = "sk-ant-api03-Your-Real-Key-Here"

The moment you push that to a public repo, the key is out in the open. And even if you delete it afterwards, it stays in the git history forever. The fix is to pull the key out of the code and store it in a separate file that git never pushes.

1. Create a .env file

In the root of your project, create a file called .env (yes, it starts with a dot) and put the key in there:

# .env
ANTHROPIC_API_KEY=sk-ant-api03-Your-Real-Key-Here

2. Tell git to ignore it (before you push anything)

This is the step that actually protects you. Create or open the .gitignore file in the root and add a line with .env:

# .gitignore
.env
node_modules

With that, git acts as if .env doesn't exist. Check it: the command below lists what git is about to push, and .env should not show up.

git status

3. Use it from the code

The code reads the key from the environment, not from the text. In Node, you pass it the file with --env-file and read it from process.env:

node --env-file=.env my-script.js
// my-script.js
const apiKey = process.env.ANTHROPIC_API_KEY

The key is never in the code. Whoever clones your repo creates their own .env with their own key. It's good practice to leave a .env.example (that one does get pushed) with the names but no values, so people know which keys are needed.

If you already pushed a key by mistake

It happens, and the right reaction is not to delete the file. Since the key landed in the history, the only safe move is to disable it:

Short rule to remember: the key lives in .env, .env lives in .gitignore, and you never paste it into the code, a chat, or a screenshot.

BUILT BY EDRA

I build websites, automations, and AI tools, and write up what I learn along the way.

More tutorials ↗