Enable TLS on a Connection
On this page
Overview
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.
Enable TLS
You can enable TLS on a connection to your MongoDB instance in the following ways:
Setting the
tls
option totrue
in yourMongoClientOptions
objectSetting the
tls
option totrue
in your connection string
A MongoClient
instance can connect with TLS if you set tls
to true
in your MongoClientOptions
object:
const client = new MongoClient(uri, { tls: true });
A MongoClient
instance can connect with TLS if you set the
tls
option to true
in your connection string:
const uri = "mongodb://<hostname>:<port>?tls=true"; const client = new MongoClient(uri, myClientSettings);
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. To disable it, set the tls
or ssl
parameter
value to false
in your connection string or MongoClientOptions
object.
To learn more about connection behavior when you use a DNS seedlist, see the SRV Connection Format section in the Server manual.
In addition to the tls
client option, the driver provides more
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.
Configure Certificates
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, we recommend that your MongoDB deployment 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 required 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.
Reference Certificates in a Client
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
Create a SecureContext Object 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.
Provide Certificate Filepaths
You can include the filepaths for your certificates as client options to
retrieve your certificates while connecting with TLS. The driver reads
these files when you call the connect()
method on your
MongoClient
instance.
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>`, tlsCertificateKeyFile: `<path to private client key>`, });
Note
CRL Files
Your TLS configuration might require that you present a certificate
revocation list (CRL) when connecting to MongoDB. Starting in version
6.0 of the driver, you can pass the filepath of your CRL file to the
tlsCRLFile
option in your connection string or your
MongoClientOptions
instance.
Create Buffer Objects to Store Certificates
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 });
SecureContext Example
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);
Additional Information
For more information about enabling TLS on a connection, see the following Server manual documentation: