MERN Stack To-Do App Tutorial
The MERN stack consists of:
MongoDB – Database
Express.js – Backend framework
React.js – Frontend library
Node.js – JavaScript runtime
In this tutorial, we’ll build a full-stack To-Do application where users can create, read, update, and delete tasks.
1. Project Overview
Features
Add new tasks
View all tasks
Mark tasks as completed
Delete tasks
Persistent data storage
Architecture
React (Frontend) → Express/Node (API) → MongoDB (Database)
2. Prerequisites
Make sure you have:
Node.js & npm installed
Basic JavaScript knowledge
MongoDB Atlas or local MongoDB
Basic React understanding
3. Backend Setup (Node.js + Express)
Step 1: Initialize Backend
mkdir todo-app
cd todo-app
mkdir backend
cd backend
npm init -y
npm install express mongoose cors dotenv
Step 2: Create Server (server.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");
});
4. Create the To-Do Model
models/Todo.js
const mongoose = require("mongoose");
const TodoSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
completed: {
type: Boolean,
default: false
}
}, { timestamps: true });
module.exports = mongoose.model("Todo", TodoSchema);
5. Create API Routes
routes/todos.js
const express = require("express");
const router = express.Router();
const Todo = require("../models/Todo");
// Get all todos
router.get("/", async (req, res) => {
const todos = await Todo.find();
res.json(todos);
});
// Create todo
router.post("/", async (req, res) => {
const newTodo = new Todo({ title: req.body.title });
const savedTodo = await newTodo.save();
res.json(savedTodo);
});
// Update todo
router.put("/:id", async (req, res) => {
const updated = await Todo.findByIdAndUpdate(
req.params.id,
{ completed: req.body.completed },
{ new: true }
);
res.json(updated);
});
// Delete todo
router.delete("/:id", async (req, res) => {
await Todo.findByIdAndDelete(req.params.id);
res.json({ message: "Todo deleted" });
});
module.exports = router;
Register Routes in server.js
app.use("/api/todos", require("./routes/todos"));
6. Frontend Setup (React)
Step 1: Create React App
cd ..
npx create-react-app frontend
cd frontend
npm install axios
7. Build the React UI
src/App.js
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [todos, setTodos] = useState([]);
const [title, setTitle] = useState("");
useEffect(() => {
axios.get("http://localhost:5000/api/todos")
.then(res => setTodos(res.data));
}, []);
const addTodo = async () => {
const res = await axios.post("http://localhost:5000/api/todos", { title });
setTodos([...todos, res.data]);
setTitle("");
};
const toggleTodo = async (id, completed) => {
const res = await axios.put(`http://localhost:5000/api/todos/${id}`, {
completed: !completed
});
setTodos(todos.map(t => t._id === id ? res.data : t));
};
const deleteTodo = async (id) => {
await axios.delete(`http://localhost:5000/api/todos/${id}`);
setTodos(todos.filter(t => t._id !== id));
};
return (
<div>
<h1>MERN To-Do App</h1>
<input
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="New task"
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map(todo => (
<li key={todo._id}>
<span
onClick={() => toggleTodo(todo._id, todo.completed)}
style={{ textDecoration: todo.completed ? "line-through" : "" }}
>
{todo.title}
</span>
<button onClick={() => deleteTodo(todo._id)}>X</button>
</li>
))}
</ul>
</div>
);
}
export default App;
8. Running the Application
Backend
cd backend
node server.js
Frontend
cd frontend
npm start
Open:
๐ http://localhost:3000
9. Project Enhancements
You can improve the app by adding:
User authentication (JWT)
Task due dates & priorities
Filtering (completed vs pending)
Styling with Tailwind or Material UI
Deployment (Vercel + Render)
10. Final Thoughts
This MERN To-Do App demonstrates:
RESTful API design
Full CRUD operations
Frontend-backend integration
Real-world full-stack workflow
It’s a perfect portfolio project for beginners learning MERN.
Learn MERN Stack Training in Hyderabad
Read More
Creating a Task Manager App in MERN
Building a Real-Time Chat App with MERN & Socket.io
๐ก Projects & Tutorials in MERN
Working with Environment Variables in Production
Visit Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments