bcrypt vs express-session vs jsonwebtoken vs passport
Architecting Secure Authentication Flows in Node.js
bcryptexpress-sessionjsonwebtokenpassportSimilar Packages:

Architecting Secure Authentication Flows in Node.js

bcrypt, express-session, jsonwebtoken, and passport form the core toolkit for implementing authentication and authorization in Node.js applications. bcrypt is a low-level library specifically designed for hashing passwords securely, ensuring that even if a database is compromised, raw passwords remain hidden. express-session manages server-side state by storing session data on the server and sending a reference ID to the client via cookies, ideal for traditional web apps. jsonwebtoken (JWT) enables stateless authentication by encoding user claims into a signed token that the client stores and sends with every request, fitting well for APIs and mobile apps. passport acts as a middleware framework that unifies these strategies, offering a modular system to plug in over 500 different authentication mechanisms (like Google, GitHub, or local username/password) while handling the complex logic of serializing and deserializing users.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bcrypt07,8011.11 MB38a year agoMIT
express-session06,35777.2 kB978 months agoMIT
jsonwebtoken018,19643.4 kB2099 months agoMIT
passport023,529157 kB3983 years agoMIT

Architecting Secure Authentication Flows in Node.js

Building a secure login system in Node.js isn't about picking one single package; it's about combining the right tools for password security, state management, and strategy flexibility. The packages bcrypt, express-session, jsonwebtoken, and passport each solve a specific part of this puzzle. Let's break down how they work together and where their technical differences matter most.

🔐 Password Security: The Non-Negotiable Base

Before you even think about sessions or tokens, you must secure the password itself. You never store plain text passwords.

bcrypt is the dedicated tool for this job. It uses a salted hashing algorithm that is intentionally slow to prevent brute-force attacks.

// bcrypt: Hashing a password before saving to DB
const bcrypt = require('bcrypt');
const saltRounds = 10;

async function registerUser(password) {
  const hash = await bcrypt.hash(password, saltRounds);
  // Save 'hash' to database, NOT the plain password
  return hash;
}

async function verifyLogin(password, storedHash) {
  const match = await bcrypt.compare(password, storedHash);
  return match; // true or false
}

None of the other packages (express-session, jsonwebtoken, passport) handle password hashing internally. If you use passport with a local strategy, you still explicitly call bcrypt inside your verification callback. Skipping bcrypt leaves your user data vulnerable.

🍪 State Management: Server-Side Sessions vs. Stateless Tokens

Once the password is verified, you need a way to keep the user logged in. This is where the architecture splits between express-session and jsonwebtoken.

express-session keeps the user data on the server. The client only holds a simple Session ID in a cookie. The server looks up the full user data in memory or a database store (like Redis) using that ID.

// express-session: Configuring middleware
const session = require('express-session');

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false } // Set to true in HTTPS
}));

// Storing user data in the session
app.post('/login', (req, res) => {
  req.session.userId = user.id; // Data lives on server
  res.send('Logged in');
});

// Accessing data later
app.get('/profile', (req, res) => {
  const id = req.session.userId; // Server retrieves data using ID
});

jsonwebtoken (JWT) moves the state to the client. The server signs a payload containing user info, and the client sends this token back with every request. The server verifies the signature without needing a database lookup for the session.

// jsonwebtoken: Signing a token
const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {
  const token = jwt.sign({ userId: user.id }, 'secret-key', { expiresIn: '1h' });
  res.json({ token }); // Client stores this
});

// Verifying token on subsequent requests
app.get('/profile', (req, res) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  const decoded = jwt.verify(token, 'secret-key');
  const userId = decoded.userId; // Data extracted directly from token
});

Trade-off: express-session makes it easy to log a user out instantly (just delete the server session). With jsonwebtoken, you cannot easily revoke a token before it expires unless you maintain a blacklist of invalid tokens, which defeats the purpose of being stateless.

🧩 Strategy Orchestration: The Role of Passport

While bcrypt, express-session, and jsonwebtoken handle specific mechanics, passport orchestrates the entire flow. It allows you to swap authentication strategies without rewriting your route logic.

passport works by defining a "strategy" (like Local, Google, or JWT) and then telling the app how to serialize the user into the session.

// passport: Setting up a Local Strategy with bcrypt
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  async (username, password, done) => {
    const user = await db.findUser(username);
    if (!user) return done(null, false);
    
    const match = await bcrypt.compare(password, user.hash);
    if (!match) return done(null, false);
    
    return done(null, user);
  }
));

// Serializing user for express-session
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
  const user = await db.findUserById(id);
  done(null, user);
});

// Using in a route
app.post('/login', passport.authenticate('local', {
  successRedirect: '/dashboard',
  failureRedirect: '/login'
}));

You can also use passport with JWTs via the passport-jwt strategy, combining the flexibility of Passport with the statelessness of JWTs.

// passport: Using JWT Strategy
const JwtStrategy = require('passport-jwt').Strategy;

passport.use(new JwtStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: 'secret-key'
  },
  async (payload, done) => {
    // Verify user still exists in DB
    const user = await db.findUserById(payload.userId);
    if (user) return done(null, user);
    return done(null, false);
  }
));

app.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
  res.json(req.user);
});

🔄 Real-World Architecture Patterns

Pattern 1: Traditional Web App (Server-Side Rendering)

For apps rendering HTML on the server (using EJS, Pug, or similar), stateful sessions are usually simpler and more secure.

  • Stack: bcrypt + express-session + passport (Local Strategy).
  • Why: Easy to invalidate sessions, built-in CSRF protection via cookies, and no need to manage token storage on the client.

Pattern 2: API-First or Mobile Backend

For SPAs (React, Vue) or mobile apps, stateless tokens reduce server load and simplify cross-domain requests.

  • Stack: bcrypt + jsonwebtoken + passport (JWT Strategy).
  • Why: The mobile app or frontend can store the JWT and send it with every API call. The API server doesn't need to query a session store for every request.

Pattern 3: Social Login Integration

When adding "Login with Google" or "Login with GitHub", passport shines by abstracting the OAuth complexity.

  • Stack: passport (OAuth Strategy) + express-session (to store the profile temporarily).
  • Why: You don't need to write the OAuth redirect logic manually. Passport handles the redirect, the callback, and verifying the social provider's signature.

⚠️ Critical Security Considerations

Regardless of the package choice, specific implementation details determine security.

Hashing Strength: With bcrypt, always use a dynamic salt round (currently 10-12 is standard). Never use MD5 or SHA1 for passwords.

// Correct usage
const hash = await bcrypt.hash(password, 12);

Token Expiration: When using jsonwebtoken, short-lived tokens are mandatory. If a token is stolen, it should expire quickly.

// Correct usage
const token = jwt.sign({ id: user.id }, secret, { expiresIn: '15m' });

Session Secret: For express-session, the secret must be a long, random string stored in environment variables, never hardcoded.

// Correct usage
app.use(session({ secret: process.env.SESSION_SECRET, ... }));

📊 Summary Comparison

Featurebcryptexpress-sessionjsonwebtokenpassport
Primary RolePassword HashingServer-Side StateStateless TokensAuth Middleware
Data StorageDatabase (Hash)Server Memory/StoreClient DeviceN/A (Orchestrator)
RevocationN/A (Change password)Instant (Delete session)Hard (Wait for expiry)Depends on strategy
Best ForAll Auth SystemsSSR Web AppsAPIs / MobileComplex/Multiple Strategies
DependenciesNoneConnect/ExpressNoneExpress/Connect

💡 Final Recommendation

Do not view these as competing options. In a professional architecture, you will almost always use bcrypt for passwords. Then, choose between express-session and jsonwebtoken based on whether your client is a server-rendered page or a separate API consumer. Finally, layer passport on top if you need to support multiple login types or want to keep your route handlers clean and standardized. This combination provides a robust, maintainable, and secure foundation for any Node.js application.

How to Choose: bcrypt vs express-session vs jsonwebtoken vs passport

  • bcrypt:

    Choose bcrypt whenever you need to store user passwords; it is the industry standard for salted hashing in Node.js. It is not a complete auth solution on its own but a critical primitive you must pair with a session or token strategy. Do not use it for generating tokens or managing login states, only for securing static secrets like passwords.

  • express-session:

    Select express-session if you are building a traditional server-rendered application (like with EJS or Pug) where keeping state on the server is acceptable and preferred. It is the right choice when you need to easily revoke access server-side or when working with legacy systems that rely on cookie-based session IDs rather than self-contained tokens.

  • jsonwebtoken:

    Opt for jsonwebtoken when building stateless APIs, microservices, or mobile backends where server-side session storage creates a bottleneck. It is ideal for scenarios requiring cross-domain authentication or when you want the client to hold the proof of identity, though you must accept the trade-off that revoking a token before it expires is difficult without extra infrastructure.

  • passport:

    Use passport when you need to support multiple login methods (such as Local, Google, and GitHub) simultaneously or when you want to decouple your authentication logic from your route handlers. It is the best choice for complex applications requiring a standardized way to handle login, logout, and user serialization across different strategies without reinventing the wheel.

README for bcrypt

node.bcrypt.js

ci

Build Status

A library to help you hash passwords.

You can read about bcrypt in Wikipedia as well as in the following article: How To Safely Store A Password

If You Are Submitting Bugs or Issues

Please verify that the NodeJS version you are using is a stable version; Unstable versions are currently not supported and issues created while using an unstable version will be closed.

If you are on a stable version of NodeJS, please provide a sufficient code snippet or log files for installation issues. The code snippet does not require you to include confidential information. However, it must provide enough information so the problem can be replicable, or it may be closed without an explanation.

Version Compatibility

Please upgrade to atleast v5.0.0 to avoid security issues mentioned below.

Node VersionBcrypt Version
0.4<= 0.4
0.6, 0.8, 0.10>= 0.5
0.11>= 0.8
4<= 2.1.0
8>= 1.0.3 < 4.0.0
10, 11>= 3
12 onwards>= 3.0.6

node-gyp only works with stable/released versions of node. Since the bcrypt module uses node-gyp to build and install, you'll need a stable version of node to use bcrypt. If you do not, you'll likely see an error that starts with:

gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead

Security Issues And Concerns

Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 characters. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis). If a string is provided, it will be encoded using UTF-8.

As should be the case with any security tool, anyone using this library should scrutinise it. If you find or suspect an issue with the code, please bring it to the maintainers' attention. We will spend some time ensuring that this library is as secure as possible.

Here is a list of BCrypt-related security issues/concerns that have come up over the years.

  • An issue with passwords was found with a version of the Blowfish algorithm developed for John the Ripper. This is not present in the OpenBSD version and is thus not a problem for this module. HT zooko.
  • Versions < 5.0.0 suffer from bcrypt wrap-around bug and will truncate passwords >= 255 characters leading to severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.
  • Versions < 5.0.0 do not handle NUL characters inside passwords properly leading to all subsequent characters being dropped and thus resulting in severely weakened passwords. Please upgrade at earliest. See this wiki page for more details.

Compatibility Note

This library supports $2a$ and $2b$ prefix bcrypt hashes. $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with $2b$ prefix.

Compatibility with hashes generated by other languages is not 100% guaranteed due to difference in character encodings. However, it should not be an issue for most cases.

Migrating from v1.0.x

Hashes generated in earlier version of bcrypt remain 100% supported in v2.x.x and later versions. In most cases, the migration should be a bump in the package.json.

Hashes generated in v2.x.x using the defaults parameters will not work in earlier versions.

Dependencies

  • NodeJS
  • node-gyp
  • Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp
  • Windows users will need the options for c# and c++ installed with their visual studio instance.
  • Python 2.x/3.x
  • OpenSSL - This is only required to build the bcrypt project if you are using versions <= 0.7.7. Otherwise, we're using the builtin node crypto bindings for seed data (which use the same OpenSSL code paths we were, but don't have the external dependency).

Install via NPM

npm install bcrypt

Note: OS X users using Xcode 4.3.1 or above may need to run the following command in their terminal prior to installing if errors occur regarding xcodebuild: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

Pre-built binaries for various NodeJS versions are made available on a best-effort basis.

Only the current stable and supported LTS releases are actively tested against.

There may be an interval between the release of the module and the availabilty of the compiled modules.

Currently, we have pre-built binaries that support the following platforms:

  1. Windows x32 and x64
  2. Linux x64 (GlibC and musl)
  3. macOS

If you face an error like this:

node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz

make sure you have the appropriate dependencies installed and configured for your platform. You can find installation instructions for the dependencies for some common platforms in this page.

Usage

async (recommended)

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Technique 2 (auto-gen a salt and hash):

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
});

Note that both techniques achieve the same end-result.

To check a password:

// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
    // result == false
});

A Note on Timing Attacks

with promises

bcrypt uses whatever Promise implementation is available in global.Promise. NodeJS >= 0.12 has a native Promise implementation built in. However, this should work in any Promises/A+ compliant implementation.

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available.

bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
    // Store hash in your password DB.
});
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash).then(function(result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) {
    // result == false
});

This is also compatible with async/await

async function checkUser(username, password) {
    //... fetch user from a db etc.

    const match = await bcrypt.compare(password, user.passwordHash);

    if(match) {
        //login
    }

    //...
}

ESM import

import bcrypt from "bcrypt";

// later
await bcrypt.compare(password, hash);

sync

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(myPlaintextPassword, salt);
// Store hash in your password DB.

Technique 2 (auto-gen a salt and hash):

const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds);
// Store hash in your password DB.

As with async, both techniques achieve the same end-result.

To check a password:

// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false

A Note on Timing Attacks

Why is async mode recommended over sync mode?

We recommend using async API if you use bcrypt on a server. Bcrypt hashing is CPU intensive which will cause the sync APIs to block the event loop and prevent your application from servicing any inbound requests or events. The async version uses a thread pool which does not block the main event loop.

API

BCrypt.

  • genSaltSync(rounds, minor)
    • rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
    • minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
  • genSalt(rounds, minor, cb)
    • rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
    • minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
    • cb - [OPTIONAL] - a callback to be fired once the salt has been generated. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • salt - Second parameter to the callback providing the generated salt.
  • hashSync(data, salt)
    • data - [REQUIRED] - the data to be encrypted.
    • salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
  • hash(data, salt, cb)
    • data - [REQUIRED] - the data to be encrypted.
    • salt - [REQUIRED] - the salt to be used to hash the password. if specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
    • cb - [OPTIONAL] - a callback to be fired once the data has been encrypted. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • encrypted - Second parameter to the callback providing the encrypted form.
  • compareSync(data, encrypted)
    • data - [REQUIRED] - data to compare.
    • encrypted - [REQUIRED] - data to be compared to.
  • compare(data, encrypted, cb)
    • data - [REQUIRED] - data to compare.
    • encrypted - [REQUIRED] - data to be compared to.
    • cb - [OPTIONAL] - a callback to be fired once the data has been compared. uses eio making it asynchronous. If cb is not specified, a Promise is returned if Promise support is available.
      • err - First parameter to the callback detailing any errors.
      • same - Second parameter to the callback providing whether the data and encrypted forms match [true | false].
  • getRounds(encrypted) - return the number of rounds used to encrypt a given hash
    • encrypted - [REQUIRED] - hash from which the number of rounds used should be extracted.

A Note on Rounds

A note about the cost: when you are hashing your data, the module will go through a series of rounds to give you a secure hash. The value you submit is not just the number of rounds the module will go through to hash your data. The module will use the value you enter and go through 2^rounds hashing iterations.

From @garthk, on a 2GHz core you can roughly expect:

rounds=8 : ~40 hashes/sec
rounds=9 : ~20 hashes/sec
rounds=10: ~10 hashes/sec
rounds=11: ~5  hashes/sec
rounds=12: 2-3 hashes/sec
rounds=13: ~1 sec/hash
rounds=14: ~1.5 sec/hash
rounds=15: ~3 sec/hash
rounds=25: ~1 hour/hash
rounds=31: 2-3 days/hash

A Note on Timing Attacks

Because it's come up multiple times in this project and other bcrypt projects, it needs to be said. The bcrypt library is not susceptible to timing attacks. From codahale/bcrypt-ruby#42:

One of the desired properties of a cryptographic hash function is preimage attack resistance, which means there is no shortcut for generating a message which, when hashed, produces a specific digest.

A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43

If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ A Lesson In Timing Attacks

However, timing attacks are real. And the comparison function is not time safe. That means that it may exit the function early in the comparison process. Timing attacks happen because of the above. We don't need to be careful that an attacker will learn anything, and our comparison function provides a comparison of hashes. It is a utility to the overall purpose of the library. If you end up using it for something else, we cannot guarantee the security of the comparator. Keep that in mind as you use the library.

Hash Info

The characters that comprise the resultant hash are ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$.

Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:

$[algorithm]$[cost]$[salt][hash]

  • 2 chars hash algorithm identifier prefix. "$2a$" or "$2b$" indicates BCrypt
  • Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
  • 16-byte (128-bit) salt, base64 encoded to 22 characters
  • 24-byte (192-bit) hash, base64 encoded to 31 characters

Example:

$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |                     |
 |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |
 |  |  salt = nOUIs5kJ7naTuTFkBy1veu
 |  |
 |  cost-factor => 10 = 2^10 rounds
 |
 hash-algorithm identifier => 2b = BCrypt

Testing

If you create a pull request, tests better pass :)

npm install
npm test

Credits

The code for this comes from a few sources:

Contributors

License

Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.