Until now, the shop's secrets were written in its code: the key that signs session cookies and the admin's password. But code travels: to the whole team, into old copies, onto GitHub. A secret that everyone who reads the code knows is no secret.
Secrets belong in environment variables: values the server gives the program when it starts, outside the code. In Node.js, process.env is an object that holds them, and a variable that isn't set is undefined there, so TypeScript gives each of them the type string | undefined. Read one and, after ||, give a default for when it isn't set, just like req.get("Authorization") || "". With the default, the result is a plain string:
const DB_FILE = process.env.DB_FILE || "shop.db";
For a secret, the default must be safe: a random value from crypto.randomBytes(16).toString("hex") that nobody can know. If a server forgets to set the admin's password, nobody can log in as admin, which is much safer than everyone who has seen the code being able to. Settings that aren't secret but change from place to place, like the address of the shop's website, come from the environment too.
The grader starts the shop with ADMIN_PASSWORD set to env-admin-pass-456 and SHOP_SITE set to https://shop.example.com. Your code must answer:
POST /login {"email": "admin@example.com", "password": "admin-pass-123"} → 401 {"error": "Wrong email or password"}
POST /login {"email": "admin@example.com", "password": "env-admin-pass-456"} → 200 {"token": "<admin>"}
GET /me (logged in as the admin) → 200 {"email": "admin@example.com", "id": 1, "role": "admin"}
POST /products {"name": "Desk", "price": 120} (as the admin) → 201 {"id": 9, "name": "Desk", "price": 120}
GET /products/1 Origin: https://shop.example.com → 200, Access-Control-Allow-Origin: https://shop.example.com
GET /products/1 Origin: http://localhost:3000 → 200, no Access-Control-Allow-Origin
Your task: create the constant SECRET_KEY, which the session line already uses, from process.env.SECRET_KEY, and read ADMIN_PASSWORD from process.env.ADMIN_PASSWORD, both with a random default. Then read SHOP_SITE from process.env.SHOP_SITE, with "http://localhost:3000" as its default. crypto is already imported.
Assignment
Follow the Coding Tutorial to read the two secrets and the shop's website from the environment.
Hint
Each value is one process.env.NAME || default. The default is what the program uses on your computer and in tests, where nothing is set, so for a secret it must be something nobody can guess. The code compiles only once all three constants exist.
Free plan: 30 tutor messages. PRO is unlimited.
