Not Publishing Your Key

The rules are short.

Not in source code. Not in git. Not in frontend JavaScript.

Read it from the environment. Add the file that holds it to .gitignore before you create the file, because the dangerous window is between creating it and remembering.

Holding a key

Python

# never
KEY = "sk_live_abc123"

# from the environment
import os
KEY = os.environ["API_KEY"]

JavaScript

// never, in frontend code,
// no matter what it is called
const KEY = "sk_live_abc123";

// Node, from the environment
const KEY = process.env.API_KEY;
Compare → Frontend code cannot hold a secret at all. Anything in the bundle is readable by every visitor. If a browser must reach an API that needs a key, the request has to go through a server you control.

✦ If it reaches a public repository, rotate it

Deleting the commit does not help. The history is public and has already been cloned, mirrored and indexed by machines that never forget. Rotating the key takes a minute and is the only action that actually works.

◈ Graded Challenge

Write build_headers(token, contact) assembling the headers for a polite authenticated request. Return an object with Accept set to "application/json" and User-Agent set to "open-record (" followed by contact and ")". When token is a non-empty string, also include Authorization set to "Bearer " followed by the token. When token is missing, null or empty, leave Authorization out entirely rather than sending an empty one.

Name it exactly: build_headers(token, contact)

2 visible + 3 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back