Setting Up Your First MERN Stack Project
Setting Up Your First MERN Stack Project
The MERN stack includes:
MongoDB – NoSQL database
Express.js – Web framework for Node.js
React.js – Frontend JavaScript library
Node.js – JavaScript runtime for backend
🛠️ Prerequisites
Before we start, make sure you have the following installed:
Node.js
MongoDB
npm (comes with Node.js)
A code editor like VS Code
📁 1. Project Structure
bash
Copy
Edit
mern-project/
├── backend/
└── frontend/
🧩 2. Set Up the Backend (Node + Express + MongoDB)
Step 1: Initialize the backend
bash
Copy
Edit
mkdir backend
cd backend
npm init -y
npm install express mongoose cors dotenv
Step 2: Create basic server
Create a file index.js in the backend/ folder:
js
Copy
Edit
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("MongoDB connected"))
.catch(err => console.error(err));
app.get('/', (req, res) => {
res.send('Hello from backend!');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Create a .env file:
env
Copy
Edit
MONGO_URI=mongodb://localhost:27017/mernapp
⚛️ 3. Set Up the Frontend (React)
Step 1: Initialize React app
bash
Copy
Edit
cd ..
npx create-react-app frontend
cd frontend
npm install axios
Step 2: Connect frontend to backend
Open frontend/src/App.js and replace with:
jsx
Copy
Edit
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
axios.get('http://localhost:5000/')
.then(res => setMessage(res.data))
.catch(err => console.error(err));
}, []);
return (
<div>
<h1>{message}</h1>
</div>
);
}
export default App;
🔗 4. Run the Project
Start backend
bash
Copy
Edit
cd backend
node index.js
Start frontend
bash
Copy
Edit
cd ../frontend
npm start
✅ You Did It!
You should now see the message from your backend in the React app.
Want me to show how to add a simple CRUD API next?
What is the MERN Stack? A Beginner's Guide
Learn MERN Stack Course in Hyderabad
Read More
What is the MERN Stack? A Beginner's Guide
Using Postman to Test Your MERN API
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment