Dev.to Security 🔐 Cybersecurity 👁 0 📖 4 min read

How to Store Passwords in Node.js the Right Way (with bcrypt)

When I built my first login system, I saved the password in the database exactly as the user typed it. It worked. Login was fine. I thought I was done. I was not. If anyone had got into that database, they could have re

When I built my first login system, I saved the password in the database exactly as the user typed it. It worked. Login was fine. I thought I was done.

I was not. If anyone had got into that database, they could have read every password in plain text. Worse, many people use the same password on other sites, so one leak can hurt them in many places.

So in this post, I will show you the simple way to do it in Node.js. It is only a few lines of code.

The one rule

Never save the real password. Save a hash of it.

A hash is a long string made from your password with a one-way function. You can turn a password into a hash, but you cannot turn the hash back into the password.

For example, the password mypassword123 might become something like this:

$2b$12$K8Hn3vYq0mZr1bQ5xLw9eOe7Jt2dUa4sVcPz6NfGhRiTyWuXoLkMa

You save that in your database. When the user logs in, you hash what they typed and compare it with the saved hash. If they match, the password is right. You never need the original.

Why not just encrypt it?

Encryption can be reversed. If you encrypt passwords, there is a key somewhere that can unlock all of them. If someone steals the key and the database, they get every password.

Hashing has no key to steal. That is why it is the right tool here.

Why not use MD5 or SHA-256?

This is a common mistake. These are hash functions, but they are made to be fast. Fast is bad for passwords, because an attacker can try billions of guesses per second on a stolen database.

For passwords, you want a hash that is slow on purpose. Good choices are:

bcrypt (old, trusted, easy to use)
argon2 (newer, also a great choice)
scrypt (built into Node.js)

I will use bcrypt here because it is the easiest to start with.

Step 1: Install bcrypt

bash
npm install bcrypt

Step 2: Hash the password on signup

const bcrypt = require("bcrypt");

const SALT_ROUNDS = 12;

async function signup(email, password) {
  const hash = await bcrypt.hash(password, SALT_ROUNDS);

  // save the hash, not the password
  await db.users.insert({ email, password: hash });
}

A few things happen here without you doing anything:

bcrypt adds a random salt to every password. This means two users with the same password get two different hashes.
The salt and the cost setting are stored inside the hash string itself, so you do not need a separate column for them.
SALT_ROUNDS is the cost. A higher number makes hashing slower and harder to attack. 12 is a good starting point for most apps. Test it on your own server, because you want hashing to take a fraction of a second, not several seconds.

Step 3: Check the password on login

async function login(email, password) {
  const user = await db.users.findOne({ email });

  if (!user) return false;

  const isMatch = await bcrypt.compare(password, user.password);
  return isMatch;
}

bcrypt.compare reads the salt from the saved hash, hashes the typed password the same way, and checks if they match.

Notice that you never "decrypt" anything. There is nothing to decrypt.

Mistakes I see a lot

  1. Logging passwords. Be careful with console.log(req.body). It can print the real password into your logs.

  2. Saving the password "just for now". Temporary code has a habit of going to production. Hash from day one.

  3. Writing your own hashing method. Do not invent your own. Use a well tested library.

  4. Using a very long password with bcrypt. bcrypt only reads the first 72 bytes of a password. For most apps this is fine, but you should know about it.

  5. Forgetting HTTPS. Hashing protects the password in your database. It does not protect it while it travels from the browser to your server. Always use HTTPS.

Can the website owner see your password?

If a site does this properly, no. The owner and the developers only see the hash. They can reset your password, but they cannot tell you the old one.

If a site can send you your old password in an email, that is a bad sign. It means the password is stored in plain text or in a form that can be reversed.

I wrote a longer post about this topic, with a simple explanation of hashing vs encryption and how different languages handle passwords. You can read it here: Can a Website Owner Retrieve Your Password from a Database?

Quick summary

Never store real passwords.
Use bcrypt, argon2, or scrypt. Do not use plain MD5 or SHA-256.
Hash on signup, compare on login.
Use HTTPS and keep passwords out of your logs.

Hashing will not save a weak password like 123456, but it makes a stolen database much less dangerous.

If you have a different way of handling passwords in your projects, or you use argon2 instead, I would like to hear about it in the comments.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.