How to set up a basic MERN stack project?

How to Set Up a Basic MERN Stack Project

The MERN stack is a popular JavaScript stack used for building full-stack web applications. It consists of:

  • MongoDB – Database

  • Express.js – Backend framework

  • React.js – Frontend framework

  • Node.js – Server runtime

Let’s go step-by-step to build a simple MERN stack project.


🧰 Prerequisites

Make sure you have installed:


πŸ“ Step 1: Create Project Folders

mkdir mern-stack-app cd mern-stack-app mkdir backend npx create-react-app frontend

Now you have:

mern-stack-app/ │ ├── backend/ └── frontend/

πŸ”§ Step 2: Set Up the Backend (Node.js + Express)

Navigate to backend/:

cd backend npm init -y npm install express mongoose cors dotenv

Create a file index.js:

const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); require('dotenv').config(); const app = express(); const PORT = process.env.PORT || 5000; app.use(cors()); app.use(express.json()); // MongoDB connection mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => { console.log('Connected to MongoDB'); }).catch(err => console.log(err)); // Sample route app.get('/', (req, res) => { res.send('Hello from Backend!'); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

Add a .env file:

MONGO_URI=mongodb://localhost:27017/mernapp

Run the backend:

node index.js

🧠 Step 3: Create a MongoDB Model (Example: User)

Create a folder models and a file User.js inside it:

const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: String }); module.exports = mongoose.model('User', userSchema);

🎯 Step 4: Set Up API Routes

Create a folder routes and file userRoutes.js:

const express = require('express'); const router = express.Router(); const User = require('../models/User'); // GET all users router.get('/', async (req, res) => { const users = await User.find(); res.json(users); }); // POST a new user router.post('/', async (req, res) => { const newUser = new User(req.body); await newUser.save(); res.json(newUser); }); module.exports = router;

Then connect routes in index.js:

const userRoutes = require('./routes/userRoutes'); app.use('/api/users', userRoutes);

🌐 Step 5: Set Up the Frontend (React)

Navigate to frontend/:

cd ../frontend npm install axios

Edit App.js:

import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [users, setUsers] = useState([]); const [name, setName] = useState(""); const [email, setEmail] = useState(""); useEffect(() => { axios.get('http://localhost:5000/api/users') .then(res => setUsers(res.data)); }, []); const addUser = () => { axios.post('http://localhost:5000/api/users', { name, email }) .then(res => setUsers([...users, res.data])); }; return ( <div> <h1>MERN Stack Users</h1> <input placeholder="Name" onChange={e => setName(e.target.value)} /> <input placeholder="Email" onChange={e => setEmail(e.target.value)} /> <button onClick={addUser}>Add User</button> <ul> {users.map(user => ( <li key={user._id}>{user.name} - {user.email}</li> ))} </ul> </div> ); } export default App;

πŸƒ Step 6: Run the App

Start Backend:

cd backend node index.js

Start Frontend:

cd frontend npm start

Visit: http://localhost:3000

You now have a working MERN Stack application!


✅ Summary

LayerTechnology
FrontendReact.js
BackendNode.js + Express
DatabaseMongoDB
CommunicationREST API using Axios


Comments

Popular posts from this blog

Tosca System Requirements and Installation Guide (Step-by-Step)

How to Install Selenium for Python Step-by-Step

Tosca Commander: A Beginner’s Overview