AI & LLMs

How to Connect React to MongoDB (the Right Way, With an Express API)

React with MongoDB: Complete Integration Guide for Modern Full-Stack Development
On this page
  1. Why React can’t talk to MongoDB directly
  2. The architecture
  3. Step 1: Create the model
  4. Step 2: Connect and add the API routes
  5. Step 3: Fetch the data in React
  6. Step 4: Send data from React
  7. Step 5: Run both in development
  8. What about “serverless” options?
  9. Deploying the React app and the API
  10. Security checklist for the API
  11. A folder structure that scales
  12. Frequently asked questions about how to connect React to MongoDB
  13. Oh hi there 👋It’s nice to meet you.
  14. Sign up to receive awesome content in your inbox.

“How do I connect React to MongoDB?” is one of the first questions every MERN developer asks, and the answer surprises many: you don’t connect them directly. React runs in the visitor’s browser; MongoDB runs on a server. Between them sits a small API, usually Express with Mongoose, which is the “E” and “N” in MERN. This guide shows why that layer is required, using a real test, and then builds the whole connection step by step.

Why React can’t talk to MongoDB directly

There are two reasons, one technical and one about security.

The driver doesn’t run in browsers. The official MongoDB driver is built for Node.js. When it was bundled for the browser, the way a React build tool would, the build failed on six Node-only modules, including fs, http, stream and timers:

Could not resolve "fs"
Could not resolve "http"
Could not resolve "process"
Could not resolve "stream"
Could not resolve "timers"

Browsers can’t open raw database connections, read files or use Node’s networking, so the driver simply can’t work there.

It would expose your database. Everything in a React app is downloaded to the visitor’s browser, where anyone can read it. A MongoDB connection string in frontend code gives every visitor your database username and password, and full access to read, change or delete all your data. An API keeps the credentials on the server and only exposes the operations you choose.

The architecture

How a MERN request flowsReact in the browser calls the Express API on Node.js, which queries MongoDB and returns JSON.Reactbrowser UIfetch("/api/…")Expressroutes + middlewarevalidate, authMongoosemodelsModel.find()MongoDBdocumentsindexesJSON response back to React
React calls the Express API; only the API knows how to reach MongoDB.
Layer Runs on Job
React The visitor’s browser Shows data and sends requests with fetch
Express API Your server (Node.js) Validates requests, checks permissions, runs queries
Mongoose Inside the API Defines schemas and talks to MongoDB
MongoDB Atlas or your own server Stores the documents

Step 1: Create the model

// server/models/Product.js
import mongoose from 'mongoose';

const productSchema = new mongoose.Schema({
  name: { type: String, required: [true, 'Name is required'], trim: true, maxlength: 80 },
  price: { type: Number, required: true, min: [0, 'Price cannot be negative'] },
  inStock: { type: Boolean, default: true },
}, { timestamps: true });

export default mongoose.model('Product', productSchema);

The schema protects your data before it reaches the database. In testing, a product with a blank name and a price of −5 failed with two clear messages: “Name is required” and “Price cannot be negative”. A valid product had its name trimmed automatically and received inStock: true and an _id. Every field type is explained in Mongoose schema types.

Step 2: Connect and add the API routes

// server/index.js
import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import Product from './models/Product.js';

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

app.get('/api/products', async (req, res) => {
  const products = await Product.find().sort({ createdAt: -1 }).limit(50).lean();
  res.json(products);
});

app.post('/api/products', async (req, res) => {
  try {
    const product = await Product.create({ name: req.body.name, price: req.body.price });
    res.status(201).json(product);
  } catch (err) {
    if (err.name === 'ValidationError') return res.status(400).json({ error: err.message });
    throw err;
  }
});

await mongoose.connect(process.env.MONGODB_URI);
app.listen(process.env.PORT ?? 5000, () => console.log('API ready'));

The connection string lives in a .env file on the server, never in React code:

# server/.env  (add .env to .gitignore)
MONGODB_URI=mongodb+srv://shop_app:PASSWORD@cluster0.abcde.mongodb.net/shop
PORT=5000

Only fields you expect are copied from req.body, so a request can’t set fields such as an admin flag. If the connection fails, fixing MongooseServerSelectionError covers the common causes, and MongoDB Atlas explained covers cloud setup.

Step 3: Fetch the data in React

// client/src/Products.jsx
import { useEffect, useState } from 'react';

export default function Products() {
  const [products, setProducts] = useState([]);
  const [status, setStatus] = useState('loading');

  useEffect(() => {
    const controller = new AbortController();
    fetch('/api/products', { signal: controller.signal })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(r.status))))
      .then((data) => { setProducts(data); setStatus('done'); })
      .catch((err) => { if (err.name !== 'AbortError') setStatus('error'); });
    return () => controller.abort();
  }, []);

  if (status === 'loading') return <p>Loading…</p>;
  if (status === 'error') return <p role="alert">Could not load products.</p>;
  return (
    <ul>
      {products.map((p) => (
        <li key={p._id}>{p.name}: ₹{p.price}</li>
      ))}
    </ul>
  );
}

Starting with an empty array and a loading state prevents the classic crash covered in fixing “Cannot read properties of undefined (reading ‘map’)”, and MongoDB’s _id makes a perfect list key.

Step 4: Send data from React

async function addProduct(name, price) {
  const res = await fetch('/api/products', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, price: Number(price) }),
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error);
  return data;
}

The Content-Type header and JSON.stringify are both required, or Express sees an empty body; see fixing req.body undefined.

Step 5: Run both in development

React’s dev server and the API run on different ports. A proxy in the React project forwards /api requests to Express, so the relative URLs above just work and there are no CORS errors:

// client/vite.config.js
export default {
  server: { proxy: { '/api': 'http://localhost:5000' } },
};

Without the proxy, requests to /api reach the React dev server, which answers with HTML and causes the error explained in fixing “is not valid JSON”. The full project setup, including running both servers with one command, is in Vite + Express: set up a full-stack MERN project.

What about “serverless” options?

You may see services that let frontends query a database directly. MongoDB’s own Atlas Data API and Device Sync were deprecated by MongoDB, so new projects shouldn’t rely on them. Modern alternatives still put server code between the browser and the database: serverless functions on platforms such as Vercel or Netlify, or full-stack frameworks such as Next.js, where server components and route handlers run on the server. The principle is the same either way: the browser never holds database credentials.

Deploying the React app and the API

In production there are two common setups. Pick based on how you host:

Setup How it works Good for
One server Express serves the React build with express.static and the API under /api A single VPS or one hosting service; no CORS needed
Two deployments React on a static host or CDN, the API on a Node.js host Scaling them separately; needs CORS and an API URL variable

With two deployments, give the React build the API’s address through an environment variable such as VITE_API_URL, set before building, and allow the frontend’s origin in the API’s CORS settings. The server side, including PM2, Nginx and HTTPS, is covered in the Node.js production checklist.

Security checklist for the API

  • Validate every request body against a schema before it reaches Mongoose, and copy only the fields you expect.
  • Protect write routes with authentication, such as sessions with Passport or JWTs.
  • Use a database user with only the permissions the app needs, and restrict Atlas network access to your server’s IP address.
  • Return generic error messages to clients and log details on the server.
  • Rate-limit login and write endpoints.

Authentication options are compared in JWT authentication in Node.js and Passport.js authentication in Express.

A folder structure that scales

Keeping the two halves in separate folders makes the boundary between browser code and server code obvious, which is exactly where security mistakes happen:

my-shop/
├── client/              React app (Vite): runs in the browser
│   ├── src/
│   └── vite.config.js   proxy /api → http://localhost:5000
└── server/              Express API: runs on Node.js
    ├── models/          Mongoose schemas
    ├── routes/          one file per resource
    ├── index.js
    └── .env             MONGODB_URI lives here, never in client/

Anything inside client/ ends up in the visitor’s browser, so it must never contain database credentials or API secrets. Anything in server/ stays on your server. If you ever find yourself importing a file from server/ into client/, stop: that code, and any secret it touches, would ship to every visitor.

Frequently asked questions about how to connect React to MongoDB

Can I use the MongoDB driver inside a React component?

No. The driver depends on Node.js modules that don’t exist in browsers, so the build fails, and putting credentials in frontend code would expose your database. Call an API instead.

Do I need Mongoose, or can I use the MongoDB driver?

Either works in the API. Mongoose adds schemas, validation and convenient models, which suit most apps; the plain driver gives more control with less abstraction.

Where should my MongoDB connection string go?

In an environment variable on the server, such as a .env file excluded from Git or your hosting platform’s settings. Never in React code.

Is Next.js different?

Next.js runs some code on the server, so server components and route handlers can query MongoDB directly. The connection string must still stay in server-only code, never in client components.

Why does my React app show an empty list even though MongoDB has data?

Check the request in the browser’s Network tab. Common causes are a missing dev proxy, a wrong database name in the connection string, so the API reads an empty database, or an API error that the frontend doesn’t display.

Can I host the React app and the API together?

Yes. Build React and let Express serve the build folder with express.static, with the API under /api. Both then share one domain, so you don’t need CORS at all.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.