Coding Hub  /  Reference  /  Node unit, Stage 2

bcrypt + jwt

How a password becomes something you can check but never read, and how a login becomes a token your API can trust. Use the filter to jump straight to what you need.

Part one: passwords

Your database will be copied one day. The only question is whether the copy is useful to whoever has it.

01 Hashing is not encryption

Encryption is two-way: with the key you can get the original back. Hashing is one-way, on purpose. Once a password is hashed there is no function anywhere that turns it back into the password.

That sounds useless until you notice what login actually needs. You never have to know the password. You only have to answer: does this guess produce the same hash?

So after a leak, an attacker holds a pile of hashes and no way to read them back. bcrypt additionally makes each guess slow, so trying a dictionary against the hashes costs real time.

Never store a password as plain text, and never email one back to a user. If a site can tell you your forgotten password, it stored it wrong.

the whole idea
// Signing up
hash("hunter2")  ->  "$2b$10$N9qo8uLO...Wq1u"   // store this

// Logging in, later
compare("hunter2", storedHash)   // true
compare("hunter3", storedHash)   // false

// What you can never do
unhash(storedHash)               // no such function, by design

02 Installing, and the two functions

bcryptjs is pure JavaScript, so it installs on any machine without a compiler. The package called bcrypt builds native code and is faster, but it breaks on machines without build tools. Use bcryptjs for class.

It is a runtime dependency. Your server hashes on every signup and compares on every login, so it belongs in dependencies.

There are only two functions you need, and both return promises.

Terminal
npm install bcryptjs
the two calls
const bcrypt = require('bcryptjs')

// Turn a password into a hash. 10 is the cost.
const hash = await bcrypt.hash('hunter2', 10)

// Check a guess against a stored hash. Returns true or false.
const ok = await bcrypt.compare(guess, hash)

03 Salt rounds

The number you pass to hash is the cost, and it is an exponent: each step up doubles the work. It is slow deliberately. Slow is the security feature.

A salt is random data mixed in before hashing, and bcrypt generates a fresh one for every password. That is why two users with the same password get different hashes, and why a precomputed table of common passwords is useless against you.

You never manage the salt yourself. bcrypt generates it, uses it, and stores it inside the hash string.

Rough times on a classroom laptop. Your numbers will differ, but the doubling will not.

cost vs time
CostRoughlyUse
8~25 msToo fast for real passwords
10~65 msThe common default. Use this.
12~250 msNoticeably slower logins; fine for sensitive data
14~1 sUsers will feel it on every login

04 Inside a bcrypt hash

A bcrypt hash is not random noise. It is four fields packed into one string, separated by $, and the salt travels with it.

That packing is what makes compare possible. To check a guess, bcrypt reads the cost and salt out of the stored string, hashes the guess the same way, and compares the results.

Paste one of your own hashes in to see it split apart. Nothing leaves your browser.

hash anatomy

05 Hashing on save

Do not hash in your controller. Put it on the model, in a pre('save') hook, and then no route can ever forget to do it.

The trap. That hook runs on every save. Without the isModified check, changing a user's name re-hashes the already-hashed password, and the account can never log in again. This bug is silent until someone tries to log in.

src/models/user.model.js
const bcrypt = require('bcryptjs')

userSchema.pre('save', async function hashPassword(){
  // Only when the password itself changed. Without this line,
  // saving any other field re-hashes the hash.
  if(!this.isModified('password')) return

  this.password = await bcrypt.hash(this.password, 10)
})

06 Checking a password

Put the comparison on the model too, as an instance method, so the controller reads like a sentence.

Two details that matter at login. The password field is normally hidden, so the login query has to ask for it back. And both failure cases — no such email, wrong password — must produce the same message, or your API becomes a tool for discovering which addresses have accounts.

on the model
userSchema.methods.comparePassword = function (guess){
  return bcrypt.compare(guess, this.password)
}
in the login controller
// .select('+password') because the schema hides it by default
const user = await User.findOne({ email }).select('+password')

// One message for both failures, on purpose
if(!user || !(await user.comparePassword(password))){
  throw ApiError.unauthorized('Invalid email or password')
}

07 Keeping the hash out of responses

Two independent guards, because one of them will eventually be bypassed by a query that needs the hash.

select: false keeps the field out of query results unless a query asks for it. The toJSON transform deletes it on the way out, which catches the login flow, where the document was deliberately loaded with the hash and then sent back in the response.

Test it the lazy way: search your JSON response for $2. Every bcrypt hash starts with it.

both guards
password:{
  type:String,
  required:[true,'password required'],
  minlength:[8,'password must be at least 8 characters'],
  select:false                 // guard one: not loaded by default
},

// ...in the schema options
toJSON:{
  virtuals:true,
  versionKey:false,
  transform(doc, ret){
    ret.id = ret._id
    delete ret._id
    delete ret.password        // guard two: never serialised
    return ret
  }
}

Part two: tokens

HTTP forgets you between requests. A token is how the next request proves it came from the same person as the last one.

08 What a JWT is

A JSON Web Token is three base64url chunks joined by dots: a header, a payload, and a signature made from the first two plus your secret.

The server does not store it. When a request arrives carrying a token, the server re-runs the signature with its secret. If it matches, the payload has not been tampered with, so the user id inside can be trusted without a lookup to "find the session". That is what stateless means.

Signed is not encrypted. Anyone holding a token can read its payload — try it in the next entry. Never put a password, an email you would not publish, or anything private inside one.

what the three parts are for
PartHoldsWho can read it
headerThe algorithm, usually HS256Anyone
payloadYour claims: sub, iat, expAnyone
signatureProof it was made with your secretOnly checkable with the secret

09 Inside a token

Paste a token from your own API. It is decoded in your browser and nothing is sent anywhere.

Notice what this proves: decoding needs no secret at all. Anyone who gets hold of a token can read every claim in it.

The standard claim names are short for a reason — they travel on every request. sub is the subject (who the token is about), iat is issued-at, exp is expiry. Both times are seconds since 1970, not milliseconds.

token decoder
header payload signature

  

10 Signing

Keep the payload small. The user's row can change at any moment, so the id is the only thing worth carrying; look the rest up when you need it.

The secret comes from the environment, never from the source file. A secret in your repository is a secret everyone with the repository has.

src/utils/jwt.js
const jwt = require('jsonwebtoken')
const { jwtSecret, jwtExpiresIn } = require('../config/env')

function signToken(user){
  // 'sub' is the standard claim for "who this token is about"
  const payload = { sub: String(user._id), role: user.role }

  return jwt.sign(payload, jwtSecret, { expiresIn: jwtExpiresIn })
}
Terminal — generating a real secret
node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"

11 Verifying

jwt.verify checks the signature and the expiry, and throws if either fails. Catch its errors and rethrow your own, so a bad token leaves your API as a clean 401 instead of an accidental 500.

Do not report which check failed to the client. Telling an attacker that the signature was close hands them a better next attempt.

There is also jwt.decode(), which reads the payload without checking the signature. It is for debugging only. Using it where you meant verify means anyone can forge any token.

src/utils/jwt.js
function verifyToken(token){
  try {
    return jwt.verify(token, jwtSecret)
  } catch (err) {
    if(err.name === 'TokenExpiredError'){
      throw ApiError.unauthorized('Token expired, please log in again')
    }
    // Forged signature, wrong secret, or plain garbage.
    // One message for all of them.
    throw ApiError.unauthorized('Invalid token')
  }
}

12 The Authorization header

The token travels in a header on every request that needs it, in one fixed shape. The word Bearer, one space, then the token.

Your middleware reads it, verifies it, loads the user, and puts the user document on req.user. Load the user rather than trusting the payload: a token stays valid until it expires, so the account may have been deleted since it was issued.

Assigning the raw payload to req.user is a common shortcut and it breaks everything downstream, because the payload has sub and no _id. Records then save with a null owner and nothing errors.

the header
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi...
src/middleware/auth.js
const requireAuth = asyncHandler(async (req, res, next) => {
  const header = req.get('authorization') || ''

  if(!header.startsWith('Bearer ')){
    throw ApiError.unauthorized('Missing or malformed Authorization header')
  }

  const payload = verifyToken(header.slice(7).trim())

  // Load the user, do not trust the payload
  const user = await User.findById(payload.sub)
  if(!user) throw ApiError.unauthorized('This account no longer exists')

  req.user = user      // the document, not the payload
  next()               // only after req.user is set
})

13 Expiry

Every token should expire. A token with no expiry is a password that never changes and that you cannot revoke.

The awkward part of stateless auth: you cannot un-issue a token. Logging out deletes it from the client, but a copied token keeps working until exp passes. Short expiry limits the damage; that is the whole defence at this level.

expiresIn accepts
ValueMeansFits
'15m'15 minutesBanking, admin panels
'12h'12 hoursA working day
'7d'7 daysClass projects, a "remember me" app
3600A bare number is secondsEasy to misread as ms. Prefer the strings.

14 Errors you will meet

Match the message to the cause before you change any code. Most of these are wiring, not logic.

message → cause
What you seeWhat it means
JsonWebTokenError: invalid signatureThe token was signed with a different secret. Usually you changed JWT_SECRET after issuing it — log in again.
JsonWebTokenError: jwt malformedNot three dot-separated parts. Often the quotes got copied with the token, or the word Bearer is missing.
TokenExpiredErrorPast exp. Log in again for a fresh token.
secretOrPrivateKey must have a valueJWT_SECRET is undefined — your .env is missing it, or it is read before dotenv loads.
Cannot read properties of undefined (reading '_id')requireAuth is not on that route, so req.user was never set.
Login always fails after a profile editThe pre('save') hook is missing its isModified check and re-hashed the hash.
Records save with ownerId: nullreq.user holds the token payload instead of the user document.
data and hash arguments requiredbcrypt.compare got undefined — the query did not .select('+password').

Part three: the rules

Short lists. Check your project against them before you hand anything in.

15 Security checklist

None of these are advanced. All of them have been the cause of a real breach somewhere.

do / never
Rule
doHash on the model, so no route can skip it
doKeep the secret in .env, and commit .env.example instead
doGive every token an expiry
doUse one message for both login failures
doEnforce a minimum password length in the schema
neverStore or log a plain password, even while debugging
neverPut anything private in a token payload
neverUse jwt.decode where you meant jwt.verify
neverCommit a real secret. If you do, rotate it — deleting the file does not remove it from git history
neverWrite your own hashing. Use the library.

16 Every function, one table

The whole surface area of both libraries that this project uses.

quick reference
CallReturnsNotes
bcrypt.hash(text, cost)Promise<string>Generates its own salt
bcrypt.compare(guess, hash)Promise<boolean>Reads the cost and salt out of hash
bcrypt.hashSync(text, cost)stringBlocks the event loop. Scripts only, never a route.
bcrypt.genSalt(cost)Promise<string>Rarely needed — hash does it for you
jwt.sign(payload, secret, opts)stringopts.expiresIn is the one you want
jwt.verify(token, secret)payload objectThrows on a bad or expired token
jwt.decode(token)payload objectNo signature check. Debugging only.