How To Connect MongoDB with ReactJS?
Last Updated :
14 Apr, 2025
MongoDB is a popular NoSQL database known for its scalability, flexibility, and high performance. When building modern web applications with ReactJS, it’s common to connect your frontend with a backend server that interacts with a database like MongoDB.
Prerequisite
Approach to connect MongoDB with ReactJS
To connect MongoDB with ReactJS, the process is divided into two main steps:
- Server-Side Connection: Set up a backend using Node.js and Express to connect to MongoDB. The backend will manage all database operations and expose APIs.
- ReactJS Client: The React frontend makes API calls to the backend to interact with MongoDB, allowing the frontend to fetch, create, update, or delete data from the database.
Connecting MongoDB with ReactJS is key for building data-driven full-stack applications. If you’re interested in mastering database connections in Node.js while working with React, the Full Stack Development with React and Node JS course provides practical insights into integrating MongoDB with full-stack applications.
Steps to Connect MongoDB with React JS
1. Create React App
To build a React application follow the below steps:
- Step 1: Create a react application using the following command
npx create-react-app foldername
- Step 2: Once it is done change your directory to the newly created application using the following command
cd foldername
- Step to run the application: Enter the following command to run the application.
npm start
Frontend Code:
JavaScript
// Frontend code
// Filename - App.js
import { useState } from 'react'
function App() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const handleOnSubmit = async (e) => {
e.preventDefault();
let result = await fetch(
'http://localhost:5000/register', {
method: "post",
body: JSON.stringify({ name, email }),
headers: {
'Content-Type': 'application/json'
}
})
result = await result.json();
console.warn(result);
if (result) {
alert("Data saved successfully");
setEmail("");
setName("");
}
}
return (
<>
<h1>This is React WebApp </h1>
<form action="">
<input type="text" placeholder="name"
value={name} onChange={(e) => setName(e.target.value)} />
<input type="email" placeholder="email"
value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit"
onClick={handleOnSubmit}>submit</button>
</form>
</>
);
}
export default App;
Note: React is a front-end framework used to build user interfaces, but it cannot directly connect to databases or handle data operations. Therefore, a backend server is required to manage these tasks.
2. Backend Setup With NodeJS
Setup NodeJs for Backend to integrate with frontend:
- Step1: Make a folder in the root directory using the following command
mkdir backend
Step 2: Once it is done change your directory to the newly created folder called backend using the following command
cd backend
- Step 3: Run the following command to create configure file
npm init -y
- Step 3: Now Install the mongoose MongoDB using the following command.
npm i express mongoose mongodb cors
- Step 4: Create a file that is index.js
touch index.js
- Step to run the application: Enter the following command to run the application.
nodemon index.js
Application Structure

Dependencies list for frontent server.
{
"name": "mongosetup",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}
Dependencies list for backend server.
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"mongodb": "^6.1.0",
"mongoose": "^7.6.1"
}
Backend Code:
JavaScript
// backend/index.js
const mongoose = require('mongoose');
const express = require('express');
const cors = require("cors");
const app = express();
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/yourDB-name', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to yourDB-name database');
}).catch((err) => {
console.log('Error connecting to database', err);
});
// Schema for users of the app
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
date: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model('users', UserSchema);
// Express setup
app.use(express.json());
app.use(cors({
origin: 'http://localhost:3000' // React frontend URL
}));
// Sample route to check if the backend is working
app.get("/", (req, resp) => {
resp.send("App is working");
});
// API to register a user
app.post("/register", async (req, resp) => {
try {
const user = new User(req.body);
let result = await user.save();
if (result) {
delete result.password; // Ensure you're not sending sensitive info
resp.status(201).send(result); // Send successful response
} else {
console.log("User already registered");
resp.status(400).send("User already registered");
}
} catch (e) {
resp.status(500).send({ message: "Something went wrong", error: e.message });
}
});
// Start the server
app.listen(5000, () => {
console.log("App is running on port 5000");
});
Step to run the application:
- Step 1: Enter the following command to run the application in Project directory.
npm start
- Step 2: Use this command in backend directory to run backend server
nodemon index.js
Output
Conclusion
Connecting MongoDB with ReactJS requires setting up a Node.js backend with Express to manage database operations. The React frontend communicates with this backend using API calls (usually with Axios) to fetch, create, update, or delete data in MongoDB. This full-stack setup allows seamless interaction between the frontend and database, enabling dynamic web applications.
Similar Reads
How To Connect Node with React?
To connect Node with React, we use React for the frontend (what users see) and Node.js for the backend (where the server logic lives). The frontend sends requests to the backend, and the backend responds with data or actions. There are many ways to connect React with Node.js, like using Axios or Fet
4 min read
How to connect ReactJS with MetaMask ?
To Connect React JS with MetaMask is important while making Web 3 applications, It will be done with Meta mask wallet which is the most used browser tool for sending and receiving signed transactions . MetaMask is a crypto wallet and a gateway to blockchain DAPP. It is used to connect our app to web
3 min read
How to connect mongodb Server with Node.js ?
mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction)Parameters: This method accept two parameters as mention
2 min read
How to Connect MongoDB with Spring Boot?
In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
5 min read
How to Connect Django with Reactjs ?
Connecting Django with React is a common approach for building full-stack applications. Django is used to manage the backend, database, APIs and React handles the User Interface on frontend. Prerequisites:A development machine with any OS (Linux/Windows/Mac).Python 3 installed.Node.js installed (ver
9 min read
How to connect ReactJS with flask API ?
Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database. ApproachTo connect Reac
4 min read
How To Create a Website in ReactJS?
ReactJS is one of the most popular JavaScript libraries for building user interfaces. It allows you to create dynamic, reusable UI components and efficiently manage state and events. In this article, we'll walk through the steps to create a basic website using ReactJS. PrerequisitesNPM & Node.js
5 min read
How to Connect Node to a MongoDB Database ?
Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
6 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read
How to Start and Stop MongoDB Server?
MongoDB, a popular NoSQL database, is used by numerous users for its flexibility, scalability, and performance. It is very important to know how to start and stop a server before deep diving into mongoDB. In this article, we'll provide a comprehensive guide on how to initiate and terminate MongoDB s
2 min read