LESSON 72 · ADVANCED4 min read

Persistence, Auth & Security

Separate storage from routes, hash passwords correctly, compare sessions with tokens, and apply a practical security baseline.

ES2024 / Node.js 20+Free to readModule 16 of 19
YOUR NEXT SMALL WINS

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.

src/store.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

src/passwords.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

src/require-token.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

src/rate-limit.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

02

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.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why should passwords be hashed rather than encrypted?
02What can anyone holding a JWT read?
03Where should a database password live?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

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.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.