Bcrypt for JavaScript (Node.js): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Bcrypt for JavaScript (Node.js): Complete Guide

\n\n

1. What It Is and Why It's Needed

\n\n

Bcrypt is an adaptive cryptographic hash function specifically designed for secure password storage. Unlike regular hash functions (MD5, SHA-1, SHA-256), which are designed for fast computation, Bcrypt is intentionally slow and resource-intensive. This makes brute-force attacks and rainbow table attacks practically infeasible. The bcrypt library for Node.js provides a simple and reliable interface for hashing and verifying passwords.

\n\n

Why use Bcrypt? When a user registers on a website, their password should never be stored in plain text. If the database is compromised, an attacker would gain access to all passwords. Bcrypt solves this problem: you hash the password with a unique salt and store only the hash. When the user logs in, you re-hash the entered password and compare it with the stored hash. Bcrypt automatically generates and embeds the salt into the result, so you don't need to store it separately.

\n\n

The key feature of Bcrypt is the ability to adjust the cost factor. The higher the cost value, the more time is required to compute the hash. As computing power increases, you can simply increase the cost, and old hashes will remain valid (the verification uses the cost stored in the hash). This makes Bcrypt resistant to future advances in hardware acceleration.

\n\n

2. Installation

\n\n

To install the Bcrypt library in a Node.js project, run the following command in the terminal (in the project root folder):

\n\n
npm install bcrypt
\n\n

After installation, you can import the library into your code:

\n\n
const bcrypt = require('bcrypt');
\n\n

If you are using ES modules (type: "module" in package.json), the import will look like this:

\n\n
import bcrypt from 'bcrypt';
\n\n

3. Quick Start — Minimal Working Example

\n\n

In this example, we hash a password and then verify it. This is the foundation for any authentication system.

\n\n
const bcrypt = require('bcrypt');\n\nconst plainPassword = 'mySuperSecretPassword123!';\nconst saltRounds = 10;\n\n// Hashing the password\nbcrypt.hash(plainPassword, saltRounds, function(err, hash) {\n    if (err) {\n        console.error('Hashing error:', err);\n        return;\n    }\n    console.log('Password hash:', hash);\n\n    // Verifying the password\n    bcrypt.compare(plainPassword, hash, function(err, result) {\n        if (err) {\n            console.error('Comparison error:', err);\n            return;\n        }\n        console.log('Password matches:', result); // true\n    });\n});
\n\n

This code does two things: creates a password hash and then checks if the original password matches this hash. Note that saltRounds determines the computational complexity (recommended value is 10–12).

\n\n

4. Main Methods/Functions/Classes

\n\n

4.1. bcrypt.hash(data, saltOrRounds, callback)

\n

Signature: bcrypt.hash(data: string | Buffer, saltOrRounds: number | string, callback: (err: Error | null, encrypted: string) => void): void

\n

What it does: Asynchronously hashes a string or Buffer. saltOrRounds can be a number (number of rounds) or a pre-generated salt (string). Returns the hash via the callback.

\n

Example:

\n
bcrypt.hash('password123', 12, (err, hash) => {\n    if (err) throw err;\n    console.log(hash); // $2b$12$...\n});
\n\n

4.2. bcrypt.hashSync(data, saltOrRounds)

\n

Signature: bcrypt.hashSync(data: string | Buffer, saltOrRounds: number | string): string

Recommendations