A RESTful API for managing todo lists with user authentication, built with Node.js, Express, and MongoDB.
- π User Authentication - JWT-based authentication with registration and login
- π CRUD Operations - Create, read, update, and delete todos
- π Authorization - Users can only access their own todos
- π Pagination - Get todos with pagination support
- π Search & Filter - Search todos by title and sort by various fields
- β Data Validation - Comprehensive input validation and error handling
- π‘οΈ Security - Password hashing, JWT tokens, and secure endpoints
- Backend: Node.js, Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JSON Web Tokens (JWT)
- Security: bcrypt for password hashing
- Environment: dotenv for configuration
| Method | Endpoint | Description | Body |
|---|---|---|---|
| POST | /api/auth/register |
Register a new user | { "name": "John Doe", "email": "john@example.com", "password": "password123" } |
| POST | /api/auth/login |
Login user | { "email": "john@example.com", "password": "password123" } |
| Method | Endpoint | Description | Headers |
|---|---|---|---|
| GET | /api/todos |
Get all todos with pagination | Authorization: Bearer <token> |
| POST | /api/todos |
Create a new todo | Authorization: Bearer <token> |
| PUT | /api/todos/:id |
Update a todo | Authorization: Bearer <token> |
| DELETE | /api/todos/:id |
Delete a todo | Authorization: Bearer <token> |
page(optional): Page number (default: 1)limit(optional): Items per page (default: 10)search(optional): Search by titlesort(optional): Sort field (default: createdAt)order(optional): Sort order - asc/desc (default: desc)
- Node.js (v14 or higher)
- MongoDB (local or Atlas)
- npm or yarn
git clone <your-repo-url>
cd todo-apinpm installCreate a .env file in the root directory:
# Server Configuration
PORT=5000
NODE_ENV=development
# Database Configuration
MONGO_URL=mongodb://127.0.0.1:27017/todo-api
# OR for MongoDB Atlas:
# MONGO_URL=mongodb+srv://username:password@cluster.mongodb.net/todo-api
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRES_IN=1h- Go to MongoDB Atlas
- Create a free account and cluster
- Create a database user
- Whitelist your IP address
- Get your connection string and update
MONGO_URLin.env
- Download and install MongoDB Community Server
- Start MongoDB service
- The default connection string should work:
mongodb://127.0.0.1:27017/todo-api
docker run -d -p 27017:27017 --name mongodb mongo:latest# Development mode (with auto-restart)
npm run dev
# Production mode
npm start
# Start without database (for testing)
npm run start-fallbackcurl http://localhost:5000/curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "password123"
}'curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'curl -X POST http://localhost:5000/api/todos \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-jwt-token>" \
-d '{
"title": "Buy groceries",
"description": "Buy milk, eggs, and bread"
}'curl -X GET "http://localhost:5000/api/todos?page=1&limit=10" \
-H "Authorization: Bearer <your-jwt-token>"{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}{
"id": "64f1c2a7e4b0f2a1c9d3b7e8",
"title": "Buy groceries",
"description": "Buy milk, eggs, and bread",
"completed": false,
"createdAt": "2023-09-01T10:00:00.000Z"
}{
"data": [
{
"id": "64f1c2a7e4b0f2a1c9d3b7e8",
"title": "Buy groceries",
"description": "Buy milk, eggs, and bread",
"completed": false,
"createdAt": "2023-09-01T10:00:00.000Z"
}
],
"page": 1,
"limit": 10,
"total": 1
}# Start production server
npm start
# Start development server with auto-restart
npm run dev
# Start server without database (for testing)
npm run start-fallback
# Test MongoDB connection
npm run check-db
# Troubleshoot MongoDB Atlas connection
npm run troubleshoottodo-api/
βββ controllers/
β βββ auth.js # Authentication logic
β βββ todoController.js # Todo CRUD operations
βββ middlewares/
β βββ auth.js # JWT authentication middleware
β βββ errorMiddleware.js # Error handling
βββ models/
β βββ User.js # User schema
β βββ Todo.js # Todo schema
βββ routes/
β βββ authRoutes.js # Authentication routes
β βββ todoRoutes.js # Todo routes
βββ app.js # Express app configuration
βββ index.js # Server entry point
βββ package.json # Dependencies and scripts
- Password Hashing: Uses bcrypt with salt rounds
- JWT Authentication: Secure token-based authentication
- Input Validation: Comprehensive validation for all inputs
- Authorization: Users can only access their own data
- Error Handling: Secure error messages without sensitive data
The API returns appropriate HTTP status codes and error messages:
400- Bad Request (validation errors)401- Unauthorized (invalid/missing token)403- Forbidden (insufficient permissions)404- Not Found (resource doesn't exist)500- Internal Server Error
{
name: String (required, 2-50 characters),
email: String (required, unique, valid email),
password: String (required, min 6 characters),
createdAt: Date,
updatedAt: Date
}{
title: String (required, max 200 characters),
description: String (optional, max 1000 characters),
completed: Boolean (default: false),
user: ObjectId (reference to User),
createdAt: Date,
updatedAt: Date
}- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the ISC License.
-
MongoDB Connection Error
- Check if MongoDB is running
- Verify connection string in
.env - Ensure IP is whitelisted (for Atlas)
-
JWT Token Issues
- Check if
JWT_SECRETis set in.env - Verify token format in Authorization header
- Check if
-
Port Already in Use
- Change
PORTin.envfile - Kill existing processes on the port
- Change
- Check the terminal output for specific error messages
- Verify your
.envconfiguration - Test MongoDB connection with
npm run check-db
- Email verification for registration
- Password reset functionality
- Todo categories and tags
- File uploads for todo attachments
- Real-time updates with WebSockets
- API rate limiting
- Comprehensive API documentation with Swagger
Happy coding! π