Sikau

Node.js · Day 14 · about 40 min

Passwords and tokens

Hash passwords, issue tokens, protect routes.

Never store a password

If your database leaks, plain passwords put every user at risk — they reuse them everywhere. Store a hash instead: a one-way fingerprint. At login, hash what they typed and compare. Then give them a token to prove who they are on later requests.

Hash + salt, then a token

import { createHash, randomBytes, randomUUID } from "node:crypto";

function hashPassword(password, salt = randomBytes(16).toString("hex")) {
  const hash = createHash("sha256").update(salt + password).digest("hex");
  return `${salt}:${hash}`;
}

function verifyPassword(password, stored) {
  const [salt] = stored.split(":");
  return hashPassword(password, salt) === stored;
}

const stored = hashPassword("momo123");
console.log("stored:", stored.slice(0, 40) + "…");
console.log("right password:", verifyPassword("momo123", stored));
console.log("wrong password:", verifyPassword("momo124", stored));

const sessions = new Map();
const token = randomUUID();
sessions.set(token, { userId: 1 });
console.log("token:", token);
  • Send tokens as Authorization: Bearer <token>; check them in middleware.
  • Prefer HTTP-only cookies for browser sessions — JavaScript can't steal them.
  • Don't roll your own for real products: use a library (Auth.js, Passport, Better Auth) and HTTPS everywhere.

The rest of this lesson

  • Why slow hashesexplain
  • Sessions and tokensexplain
  • Same hash?predict
  • Security choicesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js