Deploying a MERN App: Environment Variables, CORS and a Production Checklist

By Muhammad Osama Khan, Software Engineer. DevOps, Nov 7, 2026, 4 min read.

The settings that differ between your laptop and production: secrets, CORS, cookies behind a proxy, rate limits, health checks and graceful shutdown.

A MERN app that works on localhost can still fail on its first deploy: a missing variable, a blocked request, a cookie that never arrives. Most of it comes down to a handful of settings. This checklist covers them for the common setup of a static React front end and a separate Node API.

The usual shape

  • The React build (Vite or Create React App output) is static files, so a static host or CDN serves it.
  • The Express API runs as a long-lived Node process on a host that supports Node (a platform service, a container or your own server).
  • MongoDB runs on a managed cluster such as MongoDB Atlas, reachable only from your API.

Environment variables and secrets

Configuration belongs in the environment, not in the repository. The one rule people miss: anything in a front-end variable ends up in the browser bundle.

  • With Vite, only variables prefixed VITE_ reach the client, and they are public. Use them for an API URL, never for a secret.
  • Secrets (the MongoDB URI, JWT secrets, SMTP password) exist only on the server.
  • Commit a .env.example listing the names without values, keep the real .env in .gitignore, and fail fast if something is missing.

server/config.js

const required = ['MONGODB_URI', 'JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET', 'CLIENT_URL'];

for (const name of required) {
  if (!process.env[name]) {
    console.error('Missing environment variable: ' + name);
    process.exit(1); // better to fail at boot than at the first login
  }
}

export const config = {
  port: Number(process.env.PORT) || 4000,
  mongoUri: process.env.MONGODB_URI,
  clientUrl: process.env.CLIENT_URL,
  isProd: process.env.NODE_ENV === 'production'
};

CORS: allow exactly your front end

server/app.js

import cors from 'cors';

app.use(
  cors({
    origin: [config.clientUrl],  // the real site, not '*'
    credentials: true            // required if you use cookies
  })
);

If the browser reports a CORS error, the cause is almost always an origin that does not match exactly: https against http, www against no www, or a trailing slash.

Cookies and HTTPS behind a proxy

Hosting platforms put a proxy in front of your Node process. Express then sees plain HTTP, decides the connection is not secure and refuses to set secure cookies. Tell it to trust the first proxy.

server/app.js

if (config.isProd) app.set('trust proxy', 1);

Basic hardening

server/app.js

import helmet from 'helmet';
import rateLimit from 'express-rate-limit';

app.use(helmet()); // sensible security headers

app.use('/api/auth', rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 20,                 // 20 attempts per IP per 15 minutes
  standardHeaders: true,
  legacyHeaders: false
}));
  • In Atlas, create a database user with only the permissions the app needs, and restrict network access instead of opening it to every address.
  • Limit the request body size (express.json({ limit: '100kb' })) and validate input.
  • Never log passwords, tokens or full request bodies.

Health check and graceful shutdown

A health route lets the platform know your app is ready. Handling SIGTERM lets in-flight requests finish when a new version replaces the old one.

server/server.js

import mongoose from 'mongoose';
import app from './app.js';
import { config } from './config.js';

await mongoose.connect(config.mongoUri);
const server = app.listen(config.port, () => console.log('API on ' + config.port));

const shutdown = () => {
  server.close(async () => {
    await mongoose.connection.close();
    process.exit(0);
  });
};
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

The front end

  • Point the API URL at the deployed API through a VITE_ variable, set per environment (staging and production).
  • A client-side router needs the host to answer unknown paths with index.html, or refreshing /dashboard returns a 404. (If you prerender your pages, as this site does, each route gets its own file instead.)
  • Serve hashed JS and CSS files with a long cache lifetime, and keep index.html uncached so a new deploy shows up immediately.

Gate the deploy with CI

The cheapest safety net is a pipeline that runs before anything ships: install with npm ci, run lint and tests, build the front end, and only then deploy. A broken build then never reaches production.

Final checklist

  1. No secrets in the repo or in VITE_ variables.
  2. CORS allows only your front-end origin.
  3. trust proxy set, cookies httpOnly and secure in production.
  4. Rate limiting on login and other sensitive routes, helmet enabled.
  5. Database user with least privilege, network access restricted.
  6. Health endpoint, graceful shutdown, errors logged without secrets.
  7. CI builds and tests before each deploy, and you know how to roll back.

Frequently asked questions

Is it safe to put secrets in Vite environment variables?

No. Only variables prefixed VITE_ reach the browser, and they are public: anyone can read them in the built JavaScript. Use them for things like an API URL. Secrets such as the database URI and JWT keys must stay on the server.

Why do I get CORS errors in production but not locally?

Usually the allowed origin does not match the real one exactly: https against http, www against no www, or a trailing slash. Set the API's CORS origin to the exact deployed front-end URL.

Why are my secure cookies not set behind a proxy?

Hosting platforms put a proxy in front of Node, so Express sees plain HTTP and refuses to set secure cookies. Tell Express to trust the first proxy with app.set('trust proxy', 1) in production.

Where can I host a MERN app?

The React build is static files, so any static host or CDN works. The Express API needs a host that runs a long-lived Node process (a platform service, a container or your own server). MongoDB usually runs on a managed cluster such as MongoDB Atlas.

Keep reading

All articles · Work with me

MO
Muhammad Osama Khan