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.
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
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.
Note Workaround for an "unsafe legacy renegotiation disabled" ErrorThe Node.js driver depends on OpenSSL by default. Outdated SSL proxies can cause an unsafe legacy renegotiation disabled
error in environments using OpenSSL 3.0 or later. You can resolve this error by setting the SSL_OP_LEGACY_SERVER_CONNECT
option, as shown in the following example:
import { MongoClient } from 'mongodb';import crypto from 'crypto';const client = new MongoClient("mongodb+srv://...", { secureContext: { secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT }});
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.
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 Specify 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.
ImportantFor 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.
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:
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>`),});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 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
:
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.
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
:
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>`);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";const uri = "<connection uri>";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>`),});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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4