How to Integrate HashiCorp Vault with Node.js: Securely Manage Sensitive Data

Gowtham S - Oct 27 - - Dev Community

When working with sensitive data like passwords, API keys, or personal user information, it's essential to store them securely. Hardcoding secrets in your source code or keeping them in plain text files is a risky approach. This is where HashiCorp Vault comes into play. Vault is an open-source tool for managing secrets, such as credentials, API keys, and sensitive configurations.
In this tutorial, I will walk you through the process of:
Installing HashiCorp Vault on Windows
Integrating it with a Node.js application
Performing basic CRUD operations (Create, Read, Update, Delete) with email-password pairs stored in Vault.

Prerequisites
Before we dive in, make sure you have the following:
Node.js installed on your system.
A basic understanding of JavaScript and Node.js.
HashiCorp Vault installed.


Step 1: Installing HashiCorp Vault on Windows
Let's start by setting up Vault on your local machine.
Download Vault
Go to the official Vault downloads page and download the Windows binary.
Unzip the downloaded file and move the vault.exe file to a directory (e.g., C:\vault).

Add Vault to PATH
Open the Start Menu and search for Environment Variables.
In System Variables, find Path and click Edit.
Add the directory where vault.exe is located (C:\vault) to the list.
Open a new Command Prompt and verify the installation by running:

vault --version
Start Vault in Development Mode
Start the Vault server in development mode using this command:
vault server -dev
This command will launch Vault locally, and you should see a Root Token displayed in the terminal. Save it for later; you'll need it to authenticate.


Step 2: Setting Up a Node.js Project
Now that Vault is running, we will set up a Node.js project to interact with Vault.
Initialize a New Node.js Project
Create a new directory for your project and navigate into it:

mkdir vault-node-app cd vault-node-app

  1. Initialize a new Node.js project: npm init -y
  2. Install the required dependencies: npm install node-vault dotenv node-vault: This is the official Node.js client for Vault. dotenv: To manage environment variables.

Step 3: Integrating Vault with Node.js
Configure Environment Variables
Create a .env file in your project root directory to store Vault configurations:
VAULT_ADDR=http://127.0.0.1:8200
VAULT_TOKEN=<your-root-token>

Replace with the root token displayed when you started Vault in development mode.
Create the Node.js Script
Create a new index.js file in your project directory and paste the following code:
require('dotenv').config();
const vault = require('node-vault')({
apiVersion: 'v1',
endpoint: process.env.VAULT_ADDR,
token: process.env.VAULT_TOKEN
});
const SECRET_PATH = 'secret/data/users'; // Path to store user secrets
// Save email and password
async function saveCredentials(email, password) {
try {
const result = await vault.write(SECRET_PATH, {
data: {
[email]: { password }
}
});
console.log(
Credentials saved for ${email}:, result);
} catch (error) {
console.error('Error saving credentials:', error);
}
}
// Update credentials by email
async function updateCredentials(email, newPassword) {
try {
const result = await vault.write(SECRET_PATH, {
data: {
[email]: { password: newPassword }
}
});
console.log(
Credentials updated for ${email}:, result);
} catch (error) {
console.error('Error updating credentials:', error);
}
}
// Get credentials by email
async function getCredentials(email) {
try {
const result = await vault.read(SECRET_PATH);
const userData = result.data.data[email];
if (userData) {
console.log(
Retrieved credentials for ${email}:, userData);
} else {
console.log(
No credentials found for ${email});
}
} catch (error) {
console.error('Error retrieving credentials:', error);
}
}
// Delete credentials by email
async function deleteCredentials(email) {
try {
const result = await vault.delete(SECRET_PATH);
console.log(
Credentials deleted for ${email});
} catch (error) {
console.error('Error deleting credentials:', error);
}
}
// Example Usage
(async () => {
await saveCredentials('test@example.com', 'password123');
await getCredentials('test@example.com');
await updateCredentials('test@example.com', 'newpassword456');
await getCredentials('test@example.com');
await deleteCredentials('test@example.com');
})();

Explanation of Code
Save credentials: Stores an email and password in Vault.
Update credentials: Updates the password for the provided email.
Retrieve credentials: Fetches stored credentials using the email.
Delete credentials: Deletes the credentials for the given email.

We are using the secret/data/users path in Vault to store and manage user data.


Step 4: Running the Application
To run the application, use the following command:
node index.js
The script will:
Save the email and password to Vault.
Retrieve the credentials using the email.
Update the password.
Retrieve the updated credentials.
Delete the stored credentials.


Conclusion
By following this tutorial, you now have a fully functional Node.js application that integrates with HashiCorp Vault. This setup provides you with a secure and scalable way to manage sensitive information like email-password pairs in your application.
HashiCorp Vault is a powerful tool for storing secrets, and its integration with Node.js is relatively straightforward using the node-vault library. You can expand this setup to store other secrets like API keys, tokens, and more.
If you're building any application that requires sensitive data management, it's highly recommended to adopt a secure storage mechanism like Vault to reduce security risks.

.
Terabox Video Player