Thursday, December 4, 2025

thumbnail

HTTPS in MERN Applications

 Setting up HTTPS in MERN applications (MongoDB, Express, React, Node.js) is essential for securing data in transit, enabling secure cookies, and meeting production best practices. Below is a complete, clear guide covering local development, production, deployment options, and best practices.


HTTPS in MERN Applications


A MERN setup usually looks like this:


React (Client)

     ↓ HTTPS

Express / Node.js (API)

     ↓ Secure Connection

MongoDB (Atlas or self-hosted)



To secure this with HTTPS, you must ensure:


Your Express server uses HTTPS.


Your React app is served over HTTPS.


Your API calls (Axios/Fetch) use https://.


Any reverse proxy (Nginx, Apache, cloud load balancer) terminates TLS correctly.


1. Enabling HTTPS on the Express Backend


In production, HTTPS is typically handled by a reverse proxy (Nginx) or a cloud load balancer.

But you can run HTTPS directly in Node.js if needed.


Example: HTTPS in Node.js (self-signed certificate for dev)

const fs = require('fs');

const https = require('https');

const express = require('express');


const app = express();


// Load SSL certificate

const options = {

  key: fs.readFileSync('certs/server.key'),

  cert: fs.readFileSync('certs/server.crt'),

};


app.get('/', (req, res) => {

  res.send('Hello over HTTPS!');

});


https.createServer(options, app).listen(443, () => {

  console.log('Server running on https://localhost');

});


Where to get certificates?


Local development: generate with OpenSSL


Production: use Let’s Encrypt, Cloudflare, AWS ACM, GCP Certificates, etc.


2. Enabling HTTPS in React (Frontend)


If using create-react-app, you can enable HTTPS in development:


Windows / Mac / Linux

HTTPS=true npm start



Or add this to .env:


HTTPS=true

SSL_CRT_FILE=certs/server.crt

SSL_KEY_FILE=certs/server.key



React dev server will serve at:


https://localhost:3000


3. Making Secure API Requests


Once HTTPS is enabled, update your frontend calls:


axios.get("https://your-domain.com/api/data");



Or using fetch:


fetch("https://your-domain.com/api/login", {

  method: "POST",

  credentials: "include",

});


4. Managing HTTPS in Production (Best Options)


In almost all production deployments, Node.js does NOT terminate TLS directly. Instead, use:


Option A — HTTPS via Reverse Proxy (Nginx, Caddy, Apache)


Architecture:


React (HTTPS) → Nginx → Node.js (HTTP)


Example Nginx config:

server {

    listen 443 ssl;

    server_name example.com;


    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;


    location /api/ {

        proxy_pass http://localhost:5000/;

    }


    location / {

        root /var/www/react-app/build;

        try_files $uri /index.html;

    }

}



This is the most common and most secure method.


Option B — HTTPS using Cloud Platform Load Balancers

Popular setups:


Render → auto HTTPS


Vercel + Node backend → HTTPS ↔ serverless backend


Netlify + Node backend


AWS (ALB/ELB + EC2/ECS/Lambda)


Google Cloud Load Balancer + Cloud Run/GKE/Compute Engine


Heroku SSL


In these cases:


Load balancer terminates HTTPS


Sends HTTP (or HTTPS) traffic to your Node server


Node server listens on HTTP internally


This simplifies certificate management.


5. HTTPS with MongoDB


If using MongoDB Atlas:


All connections are TLS/SSL secured by default.


If self-hosting MongoDB:


Enable TLS on the MongoDB server:


net:

  tls:

    mode: requireTLS

    certificateKeyFile: /etc/ssl/mongodb.pem



Connect using a secure URI:


mongodb://user:pass@host:27017/dbname?ssl=true


6. HTTPS and Cookies (Authentication)


When using JWTs or sessions stored in cookies:


In production:

cookie.secure = true

cookie.sameSite = 'none'   // for cross-site cookies



Example:


res.cookie("token", token, {

  httpOnly: true,

  secure: true,

  sameSite: "none",

});



Cookies will not work over HTTP when secure: true.


7. Full Production Architecture Example

React → Nginx HTTPS → Express/Node → MongoDB Atlas



Flow:


Nginx handles SSL termination


React static files served by Nginx


Nginx proxies /api to Node


Node talks securely to MongoDB Atlas


This is the recommended MERN production setup.


8. Best Practices Checklist


✔ Use HTTPS in both frontend and backend

✔ Terminate TLS at Nginx or Cloud Load Balancer

✔ Force HTTP → HTTPS redirect

✔ Use secure, sameSite cookies for auth

✔ Never store JWT tokens in localStorage for sensitive apps

✔ Use HTTPS for MongoDB

✔ Use React .env to manage URLs:


REACT_APP_API_URL=https://api.example.com



✔ Always test certificates for proper installation


Summary


To use HTTPS in MERN applications:


Local dev: use self-signed certs or CRA HTTPS mode


Production: use a reverse proxy or cloud load balancer for TLS


Express doesn’t need to handle HTTPS directly (unless required)


Update frontend URLs to use https://


Secure cookies and authentication with secure: true


MongoDB Atlas already uses SSL


With this setup, your MERN application will be fully secure over HTTPS in both dev and production environments.


Learn MERN Stack Training in Hyderabad

Read More

Secure File Uploads in MERN

Rate Limiting & Throttling with Express

Using Helmet for Express Security

Storing Passwords Securely with bcrypt

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive