MERN Stack: MongoDB, Express.js, React, Node.js, and this is a popular
full-stack solution for fast and interactive, modern web application building. In this blog post I will guide you
through the process of making a simple web application how to use MERN stack step-by-step. It’s meant for users
having little or no development experience so it will make the understanding easy for them to get started on
full-stack development.
What is MERN Stack?
MERN consists of four technologies:
- MongoDB: NoSQL database to store data.
- Express.js: Back-end web application framework for Node.js.
- React: Front-end JavaScript library for building user interfaces.
- Node.js: JavaScript runtime environment that powers the backend server.
With these tools, you can create a full-stack web app with a React front-end, Express/Node backend, and MongoDB database.
Prerequisites
Before we begin, make sure you have:
- Node.js and npm installed: Download Node.js
- MongoDB installed: Download MongoDB
- A code editor like Visual Studio Code: Download VS Code
Step-by-Step Guide to Build a Web App Using MERN Stack
Step 1: Set Up the Project for backend in Mern
- Open your terminal or command prompt.
- Create a project folder and navigate into it:
mkdir mern-app
cd mern-app
mkdir client
mkdir server
cd server
- Initialize the project with npm:
npm init -y
- Install dependencies:
npm install express mongoose nodemon cors
Step 2: Create a Basic Backend Using Express and MongoDB
- Create a server.js file inside your project folder.
- Write the following code in
index.js
to set up a basic server: - Create a mongodb atlas account in mongodb atlas website and create free m0 database and setup , give ip access from anywhere
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// MongoDB connection
const connectDB = async () => {
try {
await mongoose.connect( "mongodb_uri" , {
});
console.log('Database is connected');
} catch (err) {
console.error('Error connecting to the database:', err);
process.exit(1);
}
};
connectDB();
app.get('/', (req, res) => {
res.send('Hello from the backend!');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
- Run the server with nodemon for hot reloading:
npx nodemon index.js,
"start": "nodemon index.js"
Add this code in script in package.json - And start your server by this command =
npm start
- Open your browser and go to http://localhost:5000 to see the backend response.
Step 3: Build the Frontend with React
- In the terminal, open another tab and create a React app inside the same project folder:
cd client
- Start the React development server:
npm start
- Open src/App.js and replace the default code with this:
import React, { useEffect, useState } from "react"; const App = () => { const [fetchname, setfetchname] = useState([]); useEffect(() => { const getdata = async () => { const username = await fetch("http://localhost:5000/get-user"); // use Domain name instead of localhost if you have it const userRes = await username.json(); const result = userRes.user; setfetchname(result); }; getdata(); }, []); return( <h2>here is your user </h2> <ul> { fetchname.map((ele) => { return( <li> {ele.name} </li> ) }) } </ul> ); }
- In the terminal, open another tab and create a React app inside the same project folder:
use Domain name instead of localhost if you have it
- Now your React frontend will display the message from the backend server!
Step 4: Connect Frontend and Backend
- Modify the React app to add user input and store it in the MongoDB database.
- In index.js, add a new route to handle user data:
// post route app.post('/add-user', async (req, res) => { const { name } = req.body; const newUser = new User({ name }); await newUser.save(); res.json({ message: 'User added!' }); }); // get route app.get("/get-user", async(req,res)=>{ const user = await User.find(); res.json({message:"user fetch successfully",user}) })
- Update to include an input form App.js in react client side project
import React, { useEffect, useState } from "react"; const App = () => { const [name, setname] = useState(""); const submitHandler = async () => { console.log("name is ", name); const response = await fetch("http://localhost:5000/add-user", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name }), }); console.log("result==", response); }; return( <form onSubmit={submitHandler}> <input type="name" name="name" placeholder="type your name" onChange={(e) => { setname(e.target.value); }} /> <button type="submit">submit</button> </form> )
- Now you can add user names through the React form, and they will be saved in MongoDB.
Step 5: Run the Full MERN Application
- Make sure both the backend and frontend servers are running.
- Use the following commands in two terminal tabs:
Backend:
npx nodemon index.js
Frontend:npm start
(inside the client folder) - Open your browser at http://localhost:3000 to see the React app. Add names through the form, and your backend
will handle the data.
Summary
Congratulations! You’ve just built a full-stack web app using the MERN stack. This app allows users to submit their
names via a React frontend, which are then stored in a MongoDB database through a Node/Express backend. At PinBlooms
Technology Pvt.Ltd., we specialize in providing end-to-end solutions like these, including MERN stack development,
web development, and app development services. Let us help you bring your next project to life!
The MERN stack is powerful, flexible, and a great tool for modern web development. As you grow more comfortable, try
adding new features, such as authentication or deploying the app online.
Tip: Make sure to take screenshots at every step—such as the backend running on “use Domain name instead of localhost if you have it” and the React app working at “use Domain name instead of localhost if you have it”—to make it easier for your users to follow along.
This guide is just the beginning. There’s so much more you can do with the MERN stack, so keep experimenting and
building awesome apps!