brainax

Keys and secrets

Lesson 6 of 26 in the course “Vibe coding”. Free, with animations and a quiz.

What an API key is

An API is how your program talks to someone else's service, like an AI model. An API key is the password for that conversation. It tells the service the request is from you and, if the service is paid, bills your account. The trap: anything in a page's code can be seen by any visitor via “View page source”.

Frontend and server

The frontend is everything that loads in the visitor's browser: the page, the buttons and their code. Anyone can read it. The server (backend) is a computer on the internet where your program runs. Visitors can't see its code. Hence the rule: secrets live only on the server. The browser asks the server, the server calls the service with the key and sends back just the result.

Never in the frontend

A key in page code or in a public repository gets found by bots fast. A repository is the project folder with its whole history of changes, for example on GitHub. Public means the whole internet can see it. Bots scan these places automatically, and you pay for strangers' requests. That's why the server makes the keyed requests, and the browser only gets the result.

Git remembers everything

Git is a program that keeps the version history of a project. Each save in it is called a commit. The trap: Git remembers everything. If a key once got into a commit, it stays in the history even if you later delete it from the file. So the file with keys must never get into Git at all. How to do that is on the next slide.

Where keys live

On your own computer keys live in a .env file, a plain text file with settings. Its name goes into .gitignore, the list of files Git must ignore. That way .env never gets into Git. On hosting, meaning the service where your site lives, keys go into the secrets section. Key leaked? Revoke it right away in the service's dashboard and create a new one.

Check yourself

  1. Where can an API key live?
    Correct answer: In hosting secrets or in .env. A key must never reach the browser or Git. A key hidden in page code is still visible via “View page source”.
  2. Why add .env to .gitignore?
    Correct answer: So the keys in .env never get into Git. .gitignore tells Git: don't save this file. That keeps keys out of the project history.
  3. A key leaked by accident. First move?
    Correct answer: Revoke it and create a new one. The key may already be copied, and deleting or hiding it won't undo that. A revoked key stops working for everyone.

← Plan first: a one-page spec Git: saves like in a game →