A production-ready RESTful API for managing tasks with MongoDB database, JWT authentication, express-validator for input validation, and comprehensive Swagger documentation. Built with Node.js and Express.js.
π Live Demo | π API Documentation
- β MongoDB Integration - Persistent data storage with Mongoose ODM
- β JWT Authentication - Secure user registration and login
- β Protected Routes - Users can only access their own tasks
- β Express Validator - Comprehensive input validation
- β Password Hashing - Secure password storage with bcryptjs
- β User-specific Tasks - Each user has their own task collection
- β Enhanced Swagger Docs - Complete API documentation with authentication
- π User registration with validation
- π Secure login with JWT token generation
- π€ Get current user profile
- π‘οΈ Password encryption with bcryptjs
- β Create, read, update, and delete tasks
- π User-specific task isolation
- π Search tasks by title
- βοΈ Filter tasks by completion status
- π Task statistics (total, completed, pending)
- π JWT-based route protection
- βοΈ Request validation with express-validator
- π Password hashing
- π« Authorization checks (users can only access their own data)
| Technology | Purpose |
|---|---|
| Node.js | Runtime environment |
| Express.js | Web framework |
| MongoDB | Database |
| Mongoose | MongoDB ODM |
| JWT | Authentication tokens |
| bcryptjs | Password hashing |
| express-validator | Input validation |
| Swagger | API documentation |
| dotenv | Environment variables |
- Node.js (v14 or higher)
- MongoDB (local or MongoDB Atlas)
- npm or yarn
-
Clone the repository
git clone https://github.com/usama-codez/Task-Manager-API-V2.git cd Task-Manager-API-V2 -
Install dependencies
npm install
-
Setup environment variables
Create a
.envfile in the root directory:PORT=3000 NODE_ENV=development # MongoDB Configuration MONGODB_URI=mongodb://localhost:27017/taskmanager # For MongoDB Atlas: mongodb+srv://<username>:<password>@cluster.mongodb.net/taskmanager # JWT Configuration JWT_SECRET=your_super_secret_jwt_key_change_this_in_production JWT_EXPIRE=7d
-
Start MongoDB (if running locally)
mongod
-
Run the application
Development mode (with nodemon):
npm run dev
Production mode:
npm start
-
Access the API
- API:
http://localhost:3000 - Swagger Docs:
http://localhost:3000/api-docs
- API:
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/users/register |
Register a new user | β |
| POST | /api/users/login |
Login user | β |
| GET | /api/users/me |
Get current user profile | β |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/tasks |
Get all user tasks | β |
| GET | /api/tasks/:id |
Get specific task | β |
| POST | /api/tasks |
Create new task | β |
| PUT | /api/tasks/:id |
Update task | β |
| DELETE | /api/tasks/:id |
Delete task | β |
| GET | /api/stats |
Get task statistics | β |
GET /api/tasks
title(string): Filter by title (case-insensitive)completed(boolean): Filter by completion status
Example: /api/tasks?title=learn&completed=false
POST /api/users/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123"
}Response:
{
"success": true,
"data": {
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"createdAt": "2025-12-04T10:30:00.000Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
},
"message": "User registered successfully"
}POST /api/users/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}Response:
{
"success": true,
"data": {
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
},
"message": "Login successful"
}POST /api/tasks
Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN
{
"title": "Learn MongoDB",
"completed": false
}Response:
{
"success": true,
"data": {
"_id": "507f191e810c19729de860ea",
"title": "Learn MongoDB",
"completed": false,
"user": "507f1f77bcf86cd799439011",
"createdAt": "2025-12-04T10:35:00.000Z",
"updatedAt": "2025-12-04T10:35:00.000Z"
},
"message": "Task created successfully"
}GET /api/tasks
Authorization: Bearer YOUR_JWT_TOKENResponse:
{
"success": true,
"count": 2,
"data": [
{
"_id": "507f191e810c19729de860ea",
"title": "Learn MongoDB",
"completed": false,
"user": "507f1f77bcf86cd799439011",
"createdAt": "2025-12-04T10:35:00.000Z",
"updatedAt": "2025-12-04T10:35:00.000Z"
}
],
"message": "Tasks retrieved successfully"
}PUT /api/tasks/507f191e810c19729de860ea
Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN
{
"title": "Master MongoDB",
"completed": true
}DELETE /api/tasks/507f191e810c19729de860ea
Authorization: Bearer YOUR_JWT_TOKENGET /api/stats
Authorization: Bearer YOUR_JWT_TOKENResponse:
{
"success": true,
"data": {
"totalTasks": 10,
"completedTasks": 6,
"pendingTasks": 4
},
"message": "Statistics retrieved successfully"
}-
Import Collection
- Use the provided
Task-Manager-API.postman_collection.json - Or create requests manually using the examples above
- Use the provided
-
Authentication Flow
- Register a new user or login
- Copy the JWT token from the response
- Add to Authorization header:
Bearer YOUR_TOKEN
-
Environment Variables (optional)
- Create variables for
base_urlandtoken - Use
{{base_url}}and{{token}}in requests
- Create variables for
Task-Manager-API-v2/
βββ api/
β βββ index.js # Vercel serverless entry point
βββ config/
β βββ db.js # MongoDB connection
βββ controllers/
β βββ authController.js # Auth logic (register, login)
β βββ taskController.js # Task CRUD operations
βββ middlewares/
β βββ auth.js # JWT authentication middleware
β βββ errorHandler.js # Global error handler
β βββ validateRequest.js # Express-validator middleware
β βββ validateTask.js # Legacy task validation
βββ models/
β βββ Task.js # Mongoose Task schema
β βββ User.js # Mongoose User schema
βββ routes/
β βββ authRoutes.js # Authentication routes
β βββ statsRoutes.js # Statistics routes
β βββ taskRoutes.js # Task CRUD routes
βββ .env # Environment variables
βββ .env.example # Environment template
βββ .gitignore # Git ignore rules
βββ app.js # Express app configuration
βββ package.json # Dependencies and scripts
βββ swagger.js # Swagger configuration
βββ README.md # Documentation
-
Password Security
- Passwords hashed using bcryptjs (10 rounds)
- Never stored or returned in plain text
-
JWT Authentication
- Tokens expire after 7 days (configurable)
- Secure token verification on protected routes
-
Data Isolation
- Users can only access their own tasks
- Authorization checks on all task operations
-
Input Validation
- All inputs validated using express-validator
- Proper error messages for invalid data
-
Create a new Web Service
- Connect your GitHub repository
- Select Node.js environment
-
Configure Environment
- Add environment variables from
.env - Set
MONGODB_URIto your MongoDB Atlas connection string
- Add environment variables from
-
Build Settings
- Build Command:
npm install - Start Command:
npm start
- Build Command:
-
Install Vercel CLI
npm i -g vercel
-
Deploy
vercel
-
Add Environment Variables
- Go to Vercel Dashboard β Settings β Environment Variables
- Add all variables from
.env
- Create a free account at MongoDB Atlas
- Create a new cluster
- Create database user and get connection string
- Update
MONGODB_URIin environment variables
Once the server is running, visit http://localhost:3000/api-docs to access the interactive Swagger documentation.
Features:
- π― Try out API endpoints directly
- π View request/response schemas
- π Test authentication with JWT tokens
- π‘ See example requests and responses
name: 2-50 characters, requiredemail: Valid email format, required, uniquepassword: Minimum 6 characters, required
email: Valid email format, requiredpassword: Required
title: 1-200 characters, requiredcompleted: Boolean, optional (defaults to false)
title: 1-200 characters, optionalcompleted: Boolean, optional- At least one field must be provided
The API returns consistent error responses:
{
"success": false,
"data": null,
"message": "Error description",
"errors": [] // Array of validation errors (if applicable)
}200- Success201- Created400- Bad Request (validation error)401- Unauthorized (not authenticated)403- Forbidden (not authorized)404- Not Found500- Internal Server Error
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the ISC License.
Your Name
- GitHub: @usama-codez
- Email: usamaakram442@gmail.com
- Express.js team for the amazing framework
- MongoDB team for the powerful database
- All open-source contributors
Made with β€οΈ using Node.js, Express.js, MongoDB, and JWT