Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Enable TLS on a Connection

On this page

  • Overview
  • Enable TLS
  • Configure Certificates
  • Reference Certificates in a Client
  • Create a SecureContext Object to Store Certificates
  • Provide Certificate Filepaths
  • Create Buffer Objects to Store Certificates
  • SecureContext Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to connect to MongoDB instances with the TLS security protocol.

To configure your connection to use TLS, enable the TLS option and provide your certificates for validation.

Tip

To learn more about TLS, see the Wikipedia entry on Transport Layer Security.

You can enable TLS on a connection to your MongoDB instance in the following ways:

  • Setting the tls option to true in your MongoClientOptions object

  • Setting the tls option to true in your connection string

Note

If you use a DNS SRV record when connecting to MongoDB by specifying the +srv modification in your connection string, you enable TLS on your connection by default.

In addition to the tls client option, the driver provides additional options to configure TLS on your connection. For testing purposes, you can set the tlsAllowInvalidHostnames, tlsAllowInvalidCertificates, and tlsInsecure client options.

Setting the tlsAllowInvalidHostnames option to true disables hostname verification, and setting the tlsAllowInvalidCertificates to true disables certificate validation. Setting the tlsInsecure option to true disables both certificate and hostname validation.

Warning

Specifying any of these options in a production environment makes your application insecure and potentially vulnerable to expired certificates and to foreign processes posing as valid client instances.

For a full list of client options, see Connection Options.

To successfully initiate a TLS request, an application must prove its identity by referencing cryptographic certificates. To connect to MongoDB with TLS, your certificates must be stored as PEM files.

Important

For production use, your MongoDB deployment should use valid certificates generated and signed by the same certificate authority. For testing, you can use self-signed certificates.

The following list describes the components that you need to establish a connection with TLS:

TLS Component
Description
Certificate Authority (CA)
One or more certificate authorities to trust when making a TLS connection.
Client Certificate
A digital certificate and key that allow the server to verify the identity of your application to establish an encrypted network connection.
Certificate Key
The client certificate private key file. This key is often included within the certificate file itself.
Passphrase
The password to decrypt the private client key if it is encrypted.

Tip

To learn more about the PEM format, see the Wikipedia entry on Privacy-Enhanced Mail.

You must reference your certificates in your MongoClientOptions object so that the server can validate them before the client connects. You can reference your certificates in the following ways:

  • Create a SecureContext object to store certificates (Recommended)

  • Provide filepath strings that point to your certificates

  • Create Buffer objects to store certificates

We recommend that you use the secureContext option to configure your TLS connection. SecureContext objects are native to Node.js and allow you to keep all your TLS options in a single reusable object.

To create a SecureContext object, import the createSecureContext() method from the tls module. Next, call the createSecureContext() method and pass the contents of your certificates in the options parameter. This method returns a SecureContext object that you can use in your MongoClientOptions object.

The following code shows how to create a SecureContext object and pass it to your client:

// Create a SecureContext object
const secureContext = tls.createSecureContext({
ca: fs.readFileSync(`<path to CA certificate>`),
cert: fs.readFileSync(`<path to public client certificate>`),
key: fs.readFileSync(`<path to private client key>`),
});
// Pass the SecureContext as a client option
const client = new MongoClient(uri, { tls: true, secureContext });

To learn more about the createSecureContext() method and the tls package, see the Node.js TLS API documentation.

For a runnable example that uses a SecureContext object, see the SecureContext Example.

You can include the filepaths for your certificates as client options to retrieve your certificates while connecting with TLS.

The following code shows how to provide certificate filepaths as options in your MongoClient:

// Pass filepaths as client options
const client = new MongoClient(uri, {
tls: true,
tlsCAFile: `<path to CA certificate>`,
tlsCertificateFile: `<path to public client certificate>`,
tlsCertificateKeyFile: `<path to private client key>`,
});

You can pass the contents of your certificate files as Buffer objects in your client options to connect with TLS.

The following code shows how to read the contents of your certificate files and pass the resulting Buffer objects as options in your MongoClient:

// Read file contents
const ca = fs.readFileSync(`<path to CA certificate>`);
const cert = fs.readFileSync(`<path to public client certificate>`);
const key = fs.readFileSync(`<path to private client key>`);
// Pass Buffers as client options
const client = new MongoClient(uri, { tls: true, ca, cert, key });

This example shows how to create a SecureContext object and a MongoClient instance that includes TLS options. The example connects to MongoDB and executes a find query:

import { MongoClient } from "mongodb";
import * as fs from "fs";
import * as tls from "tls";
// Replace the uri string with your connection string.
const uri = "<connection uri>";
// Replace the filepaths with your certificate filepaths.
const secureContext = tls.createSecureContext({
ca: fs.readFileSync(`<path to CA certificate>`),
cert: fs.readFileSync(`<path to public client certificate>`),
key: fs.readFileSync(`<path to private client key>`),
});
// Create a client with the secureContext option
const client = new MongoClient(uri, { tls: true, secureContext });
async function run() {
try {
const db = client.db("myDB");
const myColl = db.collection("myColl");
const doc = await myColl.findOne({});
console.log(doc);
} finally {
await client.close();
}
}
run().catch(console.dir);

For more information about enabling TLS on a connection, see the following Server manual documentation:

←  Network CompressionAuthentication →