MongoDB Client-Side Encryption Module

raw JSON →
7.0.0 verified Thu Apr 23 auth: no javascript

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.

error Error: Node.js version 18.x.x is not supported by mongodb-client-encryption@7.x.x
cause Attempting to use `mongodb-client-encryption` v7 with an unsupported Node.js version.
fix
Update Node.js to version 20.19.0 or newer (e.g., nvm install 20.19.0 && nvm use 20.19.0).
error TypeError: ClientEncryption is not a constructor
cause Incorrect import or `require` statement, or `mongodb-client-encryption` failed to load its native bindings.
fix
Ensure you are using 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.
cause The `local` KMS provider was configured with a master key that is not exactly 32 bytes long.
fix
Ensure the key provided to the 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.
cause Attempting to use automatic encryption features with MongoDB Community Edition or a standalone instance, which is only supported by MongoDB Enterprise or Atlas. Explicit encryption, however, works.
fix
Use MongoDB Enterprise, MongoDB Atlas, or switch to explicit encryption operations with ClientEncryption for MongoDB Community.
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.
fix Upgrade your Node.js environment to version 20.19.0 or higher. Additionally, ensure your Node.js runtime supports Node-API version 9 or later.
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.
fix Review your `ClientEncryption` configuration to remove any `CryptoCallbacks` definitions. Consult the `mongodb` driver documentation for updated methods of integrating custom crypto logic if necessary.
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.
fix Ensure your development and deployment environments running macOS are on version 11 or newer to use `mongodb-client-encryption` v7.0.0+.
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`).
fix For client-side encryption, prioritize configuring `autoEncryption` options when instantiating `MongoClient` from the `mongodb` package. Only use `mongodb-client-encryption` directly for advanced, explicit encryption scenarios after careful review of the `mongodb` driver's client-side encryption documentation.
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`.
fix Always install `mongodb-client-encryption` with a major version that aligns with your installed `mongodb` driver version. For `npm`, this often means ensuring both packages are installed with `^<major_version>.0.0` or similar compatible ranges.
npm install mongodb-client-encryption
yarn add mongodb-client-encryption
pnpm add mongodb-client-encryption

Demonstrates direct instantiation and use of `ClientEncryption` for explicit encryption and decryption of data. This showcases the core functionality provided by this library, though in most applications, client-side encryption is managed via the `mongodb` driver's `autoEncryption` settings.

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);