Generating .htpasswd Files in Node.js

Learn how to create and manage .htpasswd files for Apache authentication using Node.js.

Introduction

In Node.js, you can use the `bcrypt` library to hash passwords in a format compatible with Apache's .htpasswd files. This enables secure password storage for HTTP authentication.

Prerequisites

Ensure you have the `bcrypt` package installed in your Node.js project:

npm install bcrypt
            
Creating a New .htpasswd File

Here's how to create a new .htpasswd file with a hashed password:

const fs = require('fs');
const bcrypt = require('bcrypt');

const username = 'myUsername'; // Replace with your username
const password = 'myPassword'; // Replace with your password
const saltRounds = 10;

bcrypt.hash(password, saltRounds, (err, hash) => {
    if (err) {
        console.error(err);
        return;
    }
    const htpasswdContent = `${username}:${hash}\n`;
    fs.writeFileSync('.htpasswd', htpasswdContent);
});
            
Appending a User to an Existing .htpasswd File

To add a new user to an existing .htpasswd file:

const fs = require('fs');
const bcrypt = require('bcrypt');

const username = 'newUser'; // Replace with the new username
const password = 'newPassword'; // Replace with the new password
const saltRounds = 10;

bcrypt.hash(password, saltRounds, (err, hash) => {
    if (err) {
        console.error(err);
        return;
    }
    const htpasswdContent = `${username}:${hash}\n`;
    fs.appendFileSync('.htpasswd', htpasswdContent);
});