MongoDB Client-Side Encryption Module
raw JSON →The `mongodb-client-encryption` package is the official Node.js wrapper for `libmongocrypt`, a core library enabling Client-Side Field Level Encryption (CSFLE) for MongoDB. It is not intended for standalone use by application developers, but rather as an internal dependency of the `mongodb` Node.js driver to provide robust encryption capabilities. The current stable version is v7.0.0, released in November 2025. Releases typically align with major and minor versions of the main `mongodb` driver, with new features and breaking changes often following driver updates. Its key differentiator is providing the native bindings and core encryption logic for CSFLE, integrating seamlessly with the `mongodb` package to allow developers to encrypt sensitive data before it leaves the application, maintaining data privacy without sacrificing queryability.
Common errors
error Error: Node.js version 18.x.x is not supported by mongodb-client-encryption@7.x.x ↓
nvm install 20.19.0 && nvm use 20.19.0). error TypeError: ClientEncryption is not a constructor ↓
import { ClientEncryption } from 'mongodb-client-encryption'; for ESM and that the package installed correctly. This might involve checking for native module build errors during npm install and verifying OS/Node.js compatibility. Try npm rebuild mongodb-client-encryption. error Error: Key Management System (KMS) provider 'local' requires a 32-byte key. ↓
local KMS provider is a 32-byte Buffer. For example, key: Buffer.from('YOUR_32_BYTE_LOCAL_KEY_HERE').subarray(0, 32) or generate securely. error MongoDriverError: Queryable Encryption is not supported on MongoDB Community Edition for automatic encryption. ↓
ClientEncryption for MongoDB Community. Warnings
breaking Version 7.0.0 of `mongodb-client-encryption` requires Node.js version 20.19.0 or later. Older Node.js versions, including Node.js 18, are no longer supported. ↓
breaking Support for explicitly providing `CryptoCallbacks` was removed in v7.0.0. Custom crypto implementations must now be handled through other mechanisms or alternative integration points within the `mongodb` driver. ↓
breaking The macOS deployment target for `mongodb-client-encryption` was upgraded to macOS 11 (Big Sur) or later in v7.0.0. This means older macOS versions are no longer supported. ↓
gotcha This library is primarily an internal dependency for the `mongodb` Node.js driver and is not intended for standalone application consumption. Most users should interact with client-side encryption features through the higher-level API provided by the `mongodb` package (e.g., `MongoClient.prototype.enableAutoEncryption`). ↓
gotcha The major version of `mongodb-client-encryption` must match the major version of the `mongodb` Node.js driver it is used with for stable compatibility. For example, `mongodb@7.x.x` requires `mongodb-client-encryption@7.x.x`. ↓
Install
npm install mongodb-client-encryption yarn add mongodb-client-encryption pnpm add mongodb-client-encryption Imports
- ClientEncryption wrong
const { ClientEncryption } = require('mongodb-client-encryption')correctimport { ClientEncryption } from 'mongodb-client-encryption' - KMSProviders
import type { KMSProviders } from 'mongodb-client-encryption' - ClientEncryptionOptions
import type { ClientEncryptionOptions } from 'mongodb-client-encryption'
Quickstart
import { MongoClient, Binary } from 'mongodb';
import { ClientEncryption } from 'mongodb-client-encryption';
import * as crypto from 'crypto';
async function runEncryptionExample() {
// Ensure these environment variables are set or provide default values
const connectionString = process.env.MONGO_URI ?? 'mongodb://localhost:27017/';
const kmsProviderType = process.env.KMS_PROVIDER_TYPE ?? 'local'; // e.g., 'aws', 'azure', 'gcp', 'kmip', 'local'
const keyVaultNamespace = process.env.KEY_VAULT_NAMESPACE ?? 'encryption.__keyVault';
let kmsProviders: any;
// For a 'local' KMS provider, a 32-byte master key is required.
// In a production environment, this key should be securely managed and never hardcoded.
if (kmsProviderType === 'local') {
const localMasterKey = process.env.LOCAL_MASTER_KEY || crypto.randomBytes(96).toString('base64'); // 96 bytes for CSFLE, per MongoDB documentation
kmsProviders = {
local: { key: Buffer.from(localMasterKey, 'base64').subarray(0, 32) } // Ensure it's 32 bytes for the ClientEncryptionSettings
};
} else if (kmsProviderType === 'aws') {
// Example for AWS KMS. Replace with actual credentials/configuration.
kmsProviders = {
aws: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? 'YOUR_AWS_ACCESS_KEY_ID',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? 'YOUR_AWS_SECRET_ACCESS_KEY',
region: process.env.AWS_REGION ?? 'us-east-1'
}
};
} else {
console.error(`KMS Provider ${kmsProviderType} not supported in this example.`);
return;
}
const client = new MongoClient(connectionString);
try {
await client.connect();
const encryption = new ClientEncryption(client,
{
keyVaultNamespace,
kmsProviders
}
);
// IMPORTANT: In a real application, you would typically create or retrieve a Data Key ID
// from your key vault (e.g., using `encryption.createDataKey()`).
// For this quickstart, we'll use a placeholder UUID string for demonstration.
// Make sure this is a valid UUID (BSON Binary subtype 0x04) of an actual data key in your vault.
const dataKeyUuidString = process.env.DATA_KEY_UUID ?? '12345678123456781234567812345678'; // Example 16-byte hex representation for UUID
const dataKeyId = new Binary(Buffer.from(dataKeyUuidString.padEnd(32, '0'), 'hex'), Binary.SUBTYPE_UUID);
const dataToEncrypt = 'my highly sensitive information';
console.log('Original Data:', dataToEncrypt);
// Explicitly encrypt a field
const encryptedData = await encryption.encrypt(dataToEncrypt, {
keyId: dataKeyId,
algorithm: 'AEAD_AES256_CBC_HMAC_SHA512-Deterministic' // Or AEAD_AES256_CBC_HMAC_SHA512-Random
});
console.log('Encrypted Data (BSON Binary):', encryptedData);
// Explicitly decrypt the field
const decryptedData = await encryption.decrypt(encryptedData);
console.log('Decrypted Data:', decryptedData);
} finally {
await client.close();
}
}
runEncryptionExample().catch(console.error);