Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Client Side Field Level Encryption Hello World for Node.js
// Simple Client-Side Field Level Encryption example for Node.js
// To install: mkdir proj; cp hello_fle_node.js proj; cd proj; npm install mongodb mongodb-client-encryption --save; node hello_fle_node.js
const dbName = 'demoFLE';
const keyCollection = dbName + '.__keystore'
const dataCollection = 'people'
const url = "mongodb+srv://" + dbName; // 'mongodb://localhost'
const AWS_ACCESS_KEY = "AKIxxxxxxxxxxxxxxxxx"
const AWS_MASTER_KMS_ARN = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
const ENC_DETERM = 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
const ENC_RANDOM = 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
// SEE:
const mongo = require('mongodb')
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
(async function() {
let client;
try {
client = await MongoClient.connect(
url, {
useNewUrlParser: true,
useUnifiedTopology: true,
monitorCommands: true,
autoEncryption: {
kmsProviders: {
aws: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY,
local: {
key: Buffer.from( LOCAL_MASTER_KEY, "base64" )
keyVaultNamespace: keyCollection,
console.log("Connected to server");
console.log("Note: this example requires server-side json schema encryption specifiers.")
const db = client.db( dbName );
// Get the collection
const col = db.collection( dataCollection );
const document = {
"firstName": "Peter",
"lastName": "Parker",
"ssn": "901-01-1234",
// Insert a single document
const r = await col.insertOne( document );
assert.equal(1, r.insertedCount);
// Get first two documents that match the query
const docs = await col.find().toArray();
await console.log(docs)
} catch (err) {
// Close connection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.