← Learning Hub
Advanced

Passwords and Sign-in Tokens

Never store a password as it is. Store a hash: a one-way scramble with a random salt. When the user signs in, hash what they typed the same way and compare. Node's node:crypto has scrypt, a slow hash made for passwords.

Handling passwords and sign-in safely is one of the most important jobs of a back end. Never store passwords themselves - store slow, salted hashes - and use secure, random session tokens in httpOnly cookies. Mistakes here can expose every user's account.

Example
You can edit this code.

The same password gives a different stored string each time, because the salt is random. That stops attackers using ready-made tables of common passwords.

Tokens: staying signed in

After sign-in, the server gives the browser a token. The browser sends it with each request. A simple, safe way is a random session id saved on the server and sent in an httpOnly cookie:

Example
You can edit this code.

Security checklist

  • Use HTTPS everywhere
  • Hash passwords with scrypt, bcrypt or argon2 - never MD5 or SHA-1
  • Limit sign-in attempts (express-rate-limit)
  • Check every input on the server, even if the website already checks it
  • Use parameterised SQL queries - never glue user input into SQL
  • JWTs (jsonwebtoken package) are another option for tokens - keep them short-lived
For a real product, consider a trusted sign-in service or library (for example Passport.js, Auth.js or your cloud provider's). Security is easy to get almost right - and almost right isn't enough.
Key points
  • Hash passwords with scrypt, bcrypt or argon2 plus a salt.
  • Compare hashes with timingSafeEqual.
  • Use random session ids in httpOnly, secure cookies.

📝 Test yourself

1. How should passwords be stored?
2. Why add a random salt?
3. Fill in the cookie option that stops JavaScript in the page reading it:
res.cookie("sid", id, { : true });