Skip to content

Intermediate · Backend security · topic 39 of 54 · 25 min

Keeping secrets safe

Explanation

Secrets are values that give power: API keys, database passwords, JWT signing keys. They must never be written in code or pushed to git. Keep them in environment variables or a secret manager, change them from time to time, never print them in logs, and if one leaks, revoke it first and ask questions later.

What counts as a secret

A secret is any value that lets someone act as your app. Examples: a payment gateway key, an SMS provider token, a database connection string with its password, the key used to sign JWTs, a cloud access key. Anyone who has the secret can do what your app can do.

Think of it like this: A secret is like the key to your shop. You would not paint the key's shape on the shop sign, and you would not hand copies to every delivery boy. If a copy is lost, you change the lock the same day, before trying to find out who took it.

Never in code, never in git

Git keeps every version of every file forever. If you commit a key and delete it in the next commit, it is still in the history, and anyone with the repository can find it. Bots scan public GitHub repositories for keys within minutes of a push.

output
# .gitignore
.env
.env.local
.env.*.local
*.pem
node_modules/
A .gitignore file: git will not track these files, so local secret files stay off GitHub.

An environment variable is a named value given to your program by the system that runs it, outside the code. Your code reads process.env.NAME. On your laptop the values come from a .env file that git ignores; on the server they come from the hosting platform's settings.

javascript
// .env (never committed):  RAZORPAY_KEY_SECRET=...
const keySecret = process.env.RAZORPAY_KEY_SECRET;
if (!keySecret) {
  throw new Error('RAZORPAY_KEY_SECRET is not set');
}
// Commit a .env.example with empty values so others know which names exist
Read secrets from the environment and fail fast when one is missing (runs on a server with Node.js).

Secret managers

  • Platform settings: Vercel, Render, Railway and similar hosts have a page to set environment variables per project and environment.
  • Cloud secret managers: AWS Secrets Manager and Google Cloud Secret Manager store secrets encrypted, control who can read them, and keep an access log.
  • HashiCorp Vault (and its open-source fork OpenBao): a self-hosted tool that can also create short-lived database passwords on demand.

Rotation means replacing a secret with a new one on a schedule (for example every 90 days) or when a team member leaves. Good secret managers can rotate some secrets automatically. Design your app so a new value can be loaded without changing code.

When a key leaks

  1. Revoke or disable the leaked key at the provider first. This stops the damage right away.
  2. Create a new key and put it in your environment or secret manager.
  3. Deploy so the app uses the new key, and check it works.
  4. Check the provider's logs and bills for anything the attacker did with the old key.
  5. Remove the key from git history if needed, but remember: removing it is not enough, revoking is what protects you.
  6. Write down what happened and add a check so it does not happen again.
Tip: Turn on secret scanning. GitHub can scan repositories for known key formats, and push protection blocks a push that contains a secret before it ever reaches GitHub. Tools like gitleaks can run on your own machine before each commit.
Careful: Do not log secrets. Logging a whole request object or config object can write passwords, tokens and Authorization headers into log files that many people can read. Mask sensitive fields before logging.
PlaceOK for secrets?
Source code or gitNever
Frontend code or mobile appNever (anyone can read it)
Local .env file listed in .gitignoreYes, for development
Hosting platform environment settingsYes
Cloud secret manager or VaultYes, best for teams and production
Chat messages, email, screenshotsNo

Watch the lesson

Keeping secrets safe · 1/7

API keys DB passwords JWT secrets

API keys, database passwords and JWT signing keys are secrets. Whoever has them can act as your app.

Prefer a video by a teacher? Find free videos on “how to manage secrets environment variables api keys beginners” on YouTube ↗

In real life: The weekend AWS bill

A student pushed a side project to a public GitHub repository. The config file held a cloud access key. Within an hour, bots found the key and started many expensive servers for crypto mining. By Monday the bill was very large. The right response: disable the key in the cloud console immediately, delete the servers, create a new key stored in an environment variable, add the config file to .gitignore, turn on push protection, and contact the cloud provider's support about the charges.

Practice (0/3 done)

Task 1 · Code · Javascript

Write redact(value) that returns a NEW copy of an object where every key whose lower-case name contains one of SECRET_WORDS has its value replaced by "[REDACTED]". Go into nested objects and arrays. Keep other values and the key order the same. Do not change the original.

Task 2 · Code · Javascript

Write findSecrets(text) that scans a config text line by line. A line like NAME=value (spaces around = allowed) is a likely secret when NAME, in upper case, contains KEY, SECRET, TOKEN or PASSWORD and the value is not empty. Return an array of { line, name } objects, where line starts at 1.

Task 3 · Practice

Your team just found the SMS provider token in a public GitHub commit from last week. Write the step-by-step response plan you would follow today.

Quick quiz

Question 1

1.You committed a key, then deleted it in the next commit. Is it safe now?

Question 2

2.Where should a production database password live?

Question 3

3.A payment key leaked. What is the FIRST thing to do?

Question 4

4.What does GitHub push protection do?

Question 5

5.What is rotation?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: XSS and CSRF: attacks through the browser