Setting Up MongoDB with SSL Certificate in Node.js
When working with production MongoDB databases on Galaxy, securing your connection with SSL certificates is essential for protecting your data in transit. This guide will walk you through the process of setting up SSL-secured MongoDB connections in Node.js applications, ensuring your database communications remain encrypted and secure. SSL certificates provide an additional layer of security by encrypting data between your Node.js application and MongoDB database, preventing potential man-in-the-middle attacks and ensuring data integrity throughout the connection.
Prerequisites
Before you begin, make sure you have:
- A Galaxy MongoDB instance with SSL enabled
- Your SSL certificate file (
.crt
format) downloaded and accessible - Node.js installed
- Basic knowledge of JavaScript and MongoDB operations
Step 1: Install the MongoDB Driver
First, you'll need to install the official MongoDB driver for Node.js. Using npm, run the following command in your project directory:
npm install mongodb
Note: This guide uses the modern MongoDB driver (v4.0+). If you're using an older version, some options may differ, and we recommend upgrading to the latest version for better security and performance.
Step 2: Prepare Your SSL Certificate
Ensure your SSL certificate file is placed in an accessible location within your project structure. We recommend creating a dedicated private directory for certificates.
Step 3: Configure the MongoDB Connection
Create a connection module that handles the SSL configuration. Here's a complete example:
import { MongoClient } from 'mongodb';
const uri = 'mongodb://username:password@your-host:port/database?authSource=admin&tls=true';
const options = {
tls: true,
tlsCAFile: './path/to/certificate.crt', // Path to your SSL certificate
authSource: 'admin',
connectTimeoutMS: 10000,
serverSelectionTimeoutMS: 5000,
};
const client = new MongoClient(uri, options);
await client.connect();
Important Configuration Notes
TLS Options Explained
tls: true
: Enables TLS/SSL encryptiontlsCAFile
: Path to your certificate authority fileauthSource: 'admin'
: Specifies the authentication database (typically 'admin' for Galaxy MongoDB)- Connection timeouts help prevent hanging connections
Updated on: 30/09/2025