Persistence, Auth & Security
Separate storage from routes, hash passwords correctly, compare sessions with tokens, and apply a practical security baseline.
By the end, you’ll be able to…
- Wrap file or database access behind a repository boundary with safe writes.
- Explain password hashing, salting, and constant-time comparison.
- Choose between sessions, tokens, and API keys and apply basic server protections.
01Persistence behind a repository boundary
For a small project, a JSON file is enough: read it, mutate an array, and write it back. A database adds transactions, indexes, concurrent access, and backups. Either way, hide storage behind a repository with functions such as list, findById, create, update, and remove. Routes call the repository, so replacing the file later does not rewrite HTTP code.
Writing directly over a file can truncate it if the process dies mid-write. Write the complete document to a temporary file in the same directory, then rename it over the target; rename is atomic on common file systems. Serialize writes or use a database transaction when concurrent requests can modify the same collection.
02Passwords are hashed, never stored or encrypted
Hashing is one-way: store a derived value, then derive again at login and compare. Encryption is reversible and is the wrong tool for passwords. Use a slow, salted algorithm such as scrypt, argon2, or bcrypt; a fast hash like SHA-256 is easy to brute-force. Every password needs a unique random salt.
Node's crypto.scrypt is available without a dependency. Store the salt and derived key together, compare with timingSafeEqual, and never log or return the password. A reset flow should use a short-lived single-use token, not email the existing password, because the server should not be able to recover it.
03Sessions, tokens, and API keys
A session keeps state on the server and gives the browser an opaque cookie, usually HttpOnly, Secure, and SameSite. A token carries claims and travels on each request, often as Authorization: Bearer .... JWTs are signed, not encrypted: anyone can read the payload, so never put secrets in one. Verify the signature and expiry on every request.
API keys identify a client rather than a person. Treat them as secrets, hash them at rest, allow rotation, and scope them to the minimum permissions. Sessions, tokens, and keys all require server-side authorization for each resource; hiding a button in the client is not access control.
04A practical security baseline
Validate and normalize every input, including ids and query strings. Apply rate limits to login and write endpoints, allow only known origins in CORS, and keep secrets in environment variables. Use HTTPS in production, set security headers, and avoid returning stack traces or internal identifiers.
Security is layered: hashing protects passwords if data leaks, rate limiting slows credential stuffing, and least-privilege tokens limit damage. Log security-relevant events without logging credentials. Review dependencies and keep them patched, because many server compromises begin with a known vulnerability rather than a novel attack.
Rate limiting is not a substitute for authentication, and CORS is not a substitute for authorization. Both reduce abuse; neither decides whether a specific user may read a specific record. Put that decision in one place, close to the data, and test it with another user's id.
Apply the same checks to file paths, not just request bodies. An id from the URL must be compared as a string, never concatenated into a filesystem path, and uploads need a generated name rather than the client's. The in-memory limiter shown here resets on restart and covers one process; production uses a shared store.
The ideas worth keeping.
- Keep persistence behind a repository, write files atomically, and use transactions when concurrency matters.
- Hash passwords with a unique salt and a slow algorithm; compare with a constant-time function.
- Sessions, tokens, and API keys all require server-side authorization, rate limits, and secrets kept out of source control.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Save JSON atomically
Write saveJson(file, value) that writes the serialized value to a temporary sibling file and renames it over the target. Assume the directory already exists.
Explore a worked solution
import { rename, writeFile } from "node:fs/promises";export async function saveJson(file, value) { const temp = `${file}.tmp`; await writeFile(temp, JSON.stringify(value, null, 2), "utf8"); await rename(temp, file);}The complete new document is written before the target changes. A crash during writeFile leaves the original intact and only a temporary file behind, while rename swaps the finished file in one step.
Exercise 2: Hash and verify a password
Implement hashPassword and verifyPassword with crypto.scrypt, a random 16-byte salt, and timingSafeEqual. The stored format should be salt:key in hexadecimal.
Explore a worked solution
import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";import { promisify } from "node:util";const scrypt = promisify(scryptCallback);export async function hashPassword(password) { const salt = randomBytes(16).toString("hex"); const derived = await scrypt(password, salt, 64); return `${salt}:${derived.toString("hex")}`;}export async function verifyPassword(password, stored) { const [salt, key] = stored.split(":"); const derived = await scrypt(password, salt, 64); const expected = Buffer.from(key, "hex"); return derived.length === expected.length && timingSafeEqual(derived, expected);}The random salt makes identical passwords produce different stored values, defeating precomputed tables. timingSafeEqual compares the derived keys without an early exit that could leak how many bytes matched.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Save JSON atomically
Write saveJson(file, value) that writes the serialized value to a temporary sibling file and renames it over the target. Assume the directory already exists.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.