#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Deploying MERN Apps Using Vercel or Netlify

Vercel and Netlify both host the React front end of a MERN app very well. The Express API can also run there, but only as serverless functions, and the database stays outside on MongoDB Atlas. That works for typical CRUD apps. It does not suit WebSockets, long-running jobs or anything that needs a server that is always on. For those, deploy React on Vercel or Netlify and Express on a long-running host. This guide shows both set-ups, with the config files you need.

Deploying MERN Apps Using Vercel or Netlify

How the pieces fit

  • React (built with Vite or similar): a folder of static files served from a global CDN.
  • Express: wrapped as a function that starts on demand for each request, then may be reused for a while.
  • MongoDB: a managed Atlas cluster that your functions connect to over the internet.
  • Environment variables: connection strings and secrets stored in the platform dashboard, never in Git.

A suggested repository layout:

my-app/
  client/            # React app (Vite)
  server/
    app.js           # Express app, exported, no app.listen()
    db.js            # cached MongoDB connection
    local.js         # app.listen() for local development only
  api/index.js       # Vercel entry point
  netlify/functions/api.js   # Netlify entry point

Step 1: make Express serverless-friendly

Export the app instead of calling listen(), and reuse the database connection between invocations. Opening a new connection on every request quickly exhausts Atlas connection limits.

// server/db.js
const mongoose = require("mongoose");
const cached = global._mongoose || (global._mongoose = { conn: null, promise: null });

async function connectDB() {
  if (cached.conn) return cached.conn;
  if (!cached.promise) cached.promise = mongoose.connect(process.env.MONGODB_URI);
  cached.conn = await cached.promise;
  return cached.conn;
}
module.exports = connectDB;
// server/app.js
const express = require("express");
const connectDB = require("./db");
const Note = require("./models/Note");     // a normal Mongoose model

const app = express();
app.use(express.json());

const router = express.Router();
router.get("/health", (req, res) => res.json({ ok: true }));
router.get("/notes", async (req, res) => {
  await connectDB();
  res.json(await Note.find().sort({ createdAt: -1 }).limit(20));
});

// "/api" for Vercel and local dev; the second path covers Netlify's function URL
app.use(["/api", "/.netlify/functions/api"], router);
module.exports = app;
// server/local.js  (run with: node server/local.js)
require("dotenv").config();
require("./app").listen(5000, () => console.log("API on http://localhost:5000"));

During development, point Vite's dev-server proxy at http://localhost:5000 so the React app can call /api/... without CORS problems.

Step 2a: deploy on Vercel

Vercel turns files in the top-level api/ folder into serverless functions. An Express app is a request handler, so it can be exported directly:

// api/index.js
module.exports = require("../server/app");

Then route API paths to that function and everything else to the React app. The second rule makes client-side routes such as /notes/42 work on refresh:

// vercel.json
{
  "rewrites": [
    { "source": "/api/(.*)", "destination": "/api" },
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}
  1. Push the repository to GitHub and import it in Vercel.
  2. Set the build command (for example cd client && npm install && npm run build) and the output directory (client/dist) if Vercel does not detect them.
  3. Add MONGODB_URI, JWT_SECRET and any other secrets under Project Settings → Environment Variables.
  4. Deploy. Every push to the main branch redeploys, and every pull request gets its own preview URL.

A longer walkthrough is in deploying full-stack projects with Vercel.

Step 2b: deploy on Netlify

Netlify Functions use a handler export. The serverless-http package adapts an Express app to that format:

// netlify/functions/api.js     (npm install serverless-http)
const serverless = require("serverless-http");
const app = require("../../server/app");
module.exports.handler = serverless(app);
# netlify.toml
[build]
  command = "cd client && npm install && npm run build"
  publish = "client/dist"
  functions = "netlify/functions"

[[redirects]]
  from = "/api/*"
  to = "/.netlify/functions/api/:splat"
  status = 200

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

The first redirect sends API calls to the function. The second is the single-page-app fallback; a public/_redirects file with /* /index.html 200 does the same job. Add environment variables under Site configuration → Environment variables, then connect the GitHub repository to deploy.

Step 3: connect MongoDB Atlas

  • Create a cluster and a database user with a strong password, and copy the mongodb+srv:// connection string into MONGODB_URI.
  • Serverless functions do not have fixed IP addresses, so many projects allow access from anywhere (0.0.0.0/0) in Atlas Network Access. If you do this, rely on strong credentials and least-privilege database users. Paid plans of both platforms and Atlas offer tighter options.
  • Keep the connection caching from Step 1, or you will see "too many connections" errors under load.

For the database code itself, see CRUD operations with Node and MongoDB.

Vercel and Netlify compared for MERN

AspectVercelNetlify
Front-end hostingGit-based deploys, previews per pull request, global CDNGit-based deploys, deploy previews, global CDN
Express APIExport the app from a file in api/Wrap with serverless-http in Netlify Functions
Routing configvercel.json rewritesnetlify.toml or _redirects
Framework focusBuilt by the creators of Next.js, with first-class Next.js supportFramework-agnostic, with built-in forms and identity add-ons
Limits to checkFunction duration, memory and bundle size per planFunction duration, memory and invocations per plan

Both have free tiers with usage limits and paid plans, and the limits change, so read the current pricing pages. Pick the one whose workflow you prefer. For a standard MERN app, either works.

When to host the backend elsewhere

Run Express on a long-running service (Render, Railway, Fly.io, a cloud VM or a container on AWS) if your app needs:

  • WebSockets or Socket.io for real-time chat or live updates;
  • requests or background jobs that run longer than the function time limit;
  • scheduled tasks, in-memory caches or file uploads stored on disk.

Then set the React app's API base URL through an environment variable (for Vite, VITE_API_URL; anything prefixed VITE_ is public, so never put secrets there), and enable CORS in Express for your front-end domain only. Deploying container apps with Docker and AWS covers that route.

Deployment checklist

  • No secrets in the repository. Check .gitignore for .env.
  • Refreshing a deep link (/dashboard/settings) loads the app, not a 404.
  • /api/health returns {"ok":true} on the live URL.
  • Login works. Cookies need Secure and the right SameSite setting if the API is on another domain (see JWT authentication for MERN).
  • Errors are logged, and you know where to read the function logs on your platform.

Placed Students

Our Clients

Partners

...