{"id":17816,"library":"mongodb-client-encryption","title":"MongoDB Client-Side Encryption Module","description":"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.","status":"active","version":"7.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/mongodb-js/mongodb-client-encryption","tags":["javascript","typescript"],"install":[{"cmd":"npm install mongodb-client-encryption","lang":"bash","label":"npm"},{"cmd":"yarn add mongodb-client-encryption","lang":"bash","label":"yarn"},{"cmd":"pnpm add mongodb-client-encryption","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is an internal dependency of the `mongodb` driver and its public API is primarily exposed through the driver. It requires a compatible major version of the `mongodb` driver.","package":"mongodb","optional":false}],"imports":[{"note":"While directly importable, `ClientEncryption` is typically instantiated and managed via the `mongodb` driver's `MongoClient` for auto-encryption or explicit encryption contexts.","wrong":"const { ClientEncryption } = require('mongodb-client-encryption')","symbol":"ClientEncryption","correct":"import { ClientEncryption } from 'mongodb-client-encryption'"},{"note":"Type import for configuring Key Management System providers for `ClientEncryption`. This interface defines the shape of the `kmsProviders` object used to specify credentials for AWS, Azure, GCP, KMIP, or local KMS providers.","symbol":"KMSProviders","correct":"import type { KMSProviders } from 'mongodb-client-encryption'"},{"note":"Type import for the options object passed to the `ClientEncryption` constructor. This includes `keyVaultNamespace` and `kmsProviders`.","symbol":"ClientEncryptionOptions","correct":"import type { ClientEncryptionOptions } from 'mongodb-client-encryption'"}],"quickstart":{"code":"import { MongoClient, Binary } from 'mongodb';\nimport { ClientEncryption } from 'mongodb-client-encryption';\nimport * as crypto from 'crypto';\n\nasync function runEncryptionExample() {\n  // Ensure these environment variables are set or provide default values\n  const connectionString = process.env.MONGO_URI ?? 'mongodb://localhost:27017/';\n  const kmsProviderType = process.env.KMS_PROVIDER_TYPE ?? 'local'; // e.g., 'aws', 'azure', 'gcp', 'kmip', 'local'\n  const keyVaultNamespace = process.env.KEY_VAULT_NAMESPACE ?? 'encryption.__keyVault';\n\n  let kmsProviders: any;\n\n  // For a 'local' KMS provider, a 32-byte master key is required.\n  // In a production environment, this key should be securely managed and never hardcoded.\n  if (kmsProviderType === 'local') {\n    const localMasterKey = process.env.LOCAL_MASTER_KEY || crypto.randomBytes(96).toString('base64'); // 96 bytes for CSFLE, per MongoDB documentation\n    kmsProviders = {\n      local: { key: Buffer.from(localMasterKey, 'base64').subarray(0, 32) } // Ensure it's 32 bytes for the ClientEncryptionSettings\n    };\n  } else if (kmsProviderType === 'aws') {\n    // Example for AWS KMS. Replace with actual credentials/configuration.\n    kmsProviders = {\n      aws: {\n        accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? 'YOUR_AWS_ACCESS_KEY_ID',\n        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? 'YOUR_AWS_SECRET_ACCESS_KEY',\n        region: process.env.AWS_REGION ?? 'us-east-1'\n      }\n    };\n  } else {\n      console.error(`KMS Provider ${kmsProviderType} not supported in this example.`);\n      return;\n  }\n\n  const client = new MongoClient(connectionString);\n\n  try {\n    await client.connect();\n\n    const encryption = new ClientEncryption(client,\n      {\n        keyVaultNamespace,\n        kmsProviders\n      }\n    );\n\n    // IMPORTANT: In a real application, you would typically create or retrieve a Data Key ID\n    // from your key vault (e.g., using `encryption.createDataKey()`).\n    // For this quickstart, we'll use a placeholder UUID string for demonstration.\n    // Make sure this is a valid UUID (BSON Binary subtype 0x04) of an actual data key in your vault.\n    const dataKeyUuidString = process.env.DATA_KEY_UUID ?? '12345678123456781234567812345678'; // Example 16-byte hex representation for UUID\n    const dataKeyId = new Binary(Buffer.from(dataKeyUuidString.padEnd(32, '0'), 'hex'), Binary.SUBTYPE_UUID);\n\n    const dataToEncrypt = 'my highly sensitive information';\n\n    console.log('Original Data:', dataToEncrypt);\n\n    // Explicitly encrypt a field\n    const encryptedData = await encryption.encrypt(dataToEncrypt, {\n      keyId: dataKeyId,\n      algorithm: 'AEAD_AES256_CBC_HMAC_SHA512-Deterministic' // Or AEAD_AES256_CBC_HMAC_SHA512-Random\n    });\n\n    console.log('Encrypted Data (BSON Binary):', encryptedData);\n\n    // Explicitly decrypt the field\n    const decryptedData = await encryption.decrypt(encryptedData);\n    console.log('Decrypted Data:', decryptedData);\n\n  } finally {\n    await client.close();\n  }\n}\n\nrunEncryptionExample().catch(console.error);\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Ensure your development and deployment environments running macOS are on version 11 or newer to use `mongodb-client-encryption` v7.0.0+.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"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.","message":"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`).","severity":"gotcha","affected_versions":"all"},{"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.","message":"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`.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Update Node.js to version 20.19.0 or newer (e.g., `nvm install 20.19.0 && nvm use 20.19.0`).","cause":"Attempting to use `mongodb-client-encryption` v7 with an unsupported Node.js version.","error":"Error: Node.js version 18.x.x is not supported by mongodb-client-encryption@7.x.x"},{"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`.","cause":"Incorrect import or `require` statement, or `mongodb-client-encryption` failed to load its native bindings.","error":"TypeError: ClientEncryption is not a constructor"},{"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.","cause":"The `local` KMS provider was configured with a master key that is not exactly 32 bytes long.","error":"Error: Key Management System (KMS) provider 'local' requires a 32-byte key."},{"fix":"Use MongoDB Enterprise, MongoDB Atlas, or switch to explicit encryption operations with `ClientEncryption` for MongoDB Community.","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.","error":"MongoDriverError: Queryable Encryption is not supported on MongoDB Community Edition for automatic encryption."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}