Getting Started with MERN Stack Development
The MERN stack — MongoDB, Express.js, React, and Node.js — is one of the most popular technology combinations for building full-stack web applications. This guide walks you through setting up your first MERN project from scratch.
What You Will Build
By the end of this guide, you will have a working application with:
- A Node.js + Express REST API
- MongoDB for data storage
- A React frontend that consumes the API
Prerequisites
- Node.js 18+ installed
- Basic JavaScript knowledge
- A terminal / command prompt
1. Setting Up the Backend
Create your project folder and initialise the Node.js server:
mkdir my-mern-app
cd my-mern-app
mkdir server
cd server
npm init -y
npm install express mongoose cors dotenv
Create server/index.js:
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) .then(() => console.log('MongoDB connected')) .catch(err => console.error(err));
app.listen(5000, () => console.log('Server running on port 5000'));
2. Defining a Mongoose Model
// server/models/Task.js
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({ title: { type: String, required: true }, completed: { type: Boolean, default: false }, createdAt: { type: Date, default: Date.now } });
module.exports = mongoose.model('Task', taskSchema);
3. Creating API Routes
// server/routes/tasks.js
const express = require('express');
const Task = require('../models/Task');
const router = express.Router();
router.get('/', async (req, res) => { const tasks = await Task.find().sort({ createdAt: -1 }); res.json(tasks); });
router.post('/', async (req, res) => { const task = new Task({ title: req.body.title }); await task.save(); res.status(201).json(task); });
module.exports = router;
4. Setting Up the React Frontend
cd ..
npx create-react-app client
cd client
npm install axios
5. Fetching Data in React
import { useState, useEffect } from 'react';
import axios from 'axios';
function App() { const [tasks, setTasks] = useState([]);
useEffect(() => { axios.get('http://localhost:5000/api/tasks') .then(res => setTasks(res.data)); }, []);
return ( <ul> {tasks.map(task => <li key={task._id}>{task.title}</li>)} </ul> ); }
export default App;
Next Steps
- Add authentication with JWT
- Deploy the backend to Railway or Render
- Deploy the frontend to Vercel
- Add a proper folder structure with controllers and middleware
