Skip to content

Repository files navigation

πŸ“ Task Manager API v2

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

Deploy to Vercel


πŸš€ What's New in v2

  • βœ… 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

πŸ“‹ Features

Authentication

  • πŸ” User registration with validation
  • πŸ”‘ Secure login with JWT token generation
  • πŸ‘€ Get current user profile
  • πŸ›‘οΈ Password encryption with bcryptjs

Task Management

  • βœ… Create, read, update, and delete tasks
  • πŸ”’ User-specific task isolation
  • πŸ” Search tasks by title
  • βœ”οΈ Filter tasks by completion status
  • πŸ“Š Task statistics (total, completed, pending)

Security & Validation

  • πŸ” JWT-based route protection
  • βœ”οΈ Request validation with express-validator
  • πŸ”’ Password hashing
  • 🚫 Authorization checks (users can only access their own data)

πŸ› οΈ Tech Stack

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

πŸ“¦ Installation

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (local or MongoDB Atlas)
  • npm or yarn

Steps

  1. Clone the repository

    git clone https://github.com/usama-codez/Task-Manager-API-V2.git
    cd Task-Manager-API-V2
  2. Install dependencies

    npm install
  3. Setup environment variables

    Create a .env file 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
  4. Start MongoDB (if running locally)

    mongod
  5. Run the application

    Development mode (with nodemon):

    npm run dev

    Production mode:

    npm start
  6. Access the API

    • API: http://localhost:3000
    • Swagger Docs: http://localhost:3000/api-docs

🌐 API Endpoints

Authentication Endpoints

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 βœ…

Task Endpoints

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 βœ…

Query Parameters

GET /api/tasks

  • title (string): Filter by title (case-insensitive)
  • completed (boolean): Filter by completion status

Example: /api/tasks?title=learn&completed=false


πŸ“€ API Usage Examples

1. Register a New User

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"
}

2. Login

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"
}

3. Create a Task (Protected Route)

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"
}

4. Get All Tasks (Protected Route)

GET /api/tasks
Authorization: Bearer YOUR_JWT_TOKEN

Response:

{
  "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"
}

5. Update a Task

PUT /api/tasks/507f191e810c19729de860ea
Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN

{
  "title": "Master MongoDB",
  "completed": true
}

6. Delete a Task

DELETE /api/tasks/507f191e810c19729de860ea
Authorization: Bearer YOUR_JWT_TOKEN

7. Get Task Statistics

GET /api/stats
Authorization: Bearer YOUR_JWT_TOKEN

Response:

{
  "success": true,
  "data": {
    "totalTasks": 10,
    "completedTasks": 6,
    "pendingTasks": 4
  },
  "message": "Statistics retrieved successfully"
}

πŸ§ͺ Testing with Postman

  1. Import Collection

    • Use the provided Task-Manager-API.postman_collection.json
    • Or create requests manually using the examples above
  2. Authentication Flow

    • Register a new user or login
    • Copy the JWT token from the response
    • Add to Authorization header: Bearer YOUR_TOKEN
  3. Environment Variables (optional)

    • Create variables for base_url and token
    • Use {{base_url}} and {{token}} in requests

πŸ“ Project Structure

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

πŸ”’ Security Features

  1. Password Security

    • Passwords hashed using bcryptjs (10 rounds)
    • Never stored or returned in plain text
  2. JWT Authentication

    • Tokens expire after 7 days (configurable)
    • Secure token verification on protected routes
  3. Data Isolation

    • Users can only access their own tasks
    • Authorization checks on all task operations
  4. Input Validation

    • All inputs validated using express-validator
    • Proper error messages for invalid data

🌍 Deployment

Deploying to Render

  1. Create a new Web Service

    • Connect your GitHub repository
    • Select Node.js environment
  2. Configure Environment

    • Add environment variables from .env
    • Set MONGODB_URI to your MongoDB Atlas connection string
  3. Build Settings

    • Build Command: npm install
    • Start Command: npm start

Deploying to Vercel

  1. Install Vercel CLI

    npm i -g vercel
  2. Deploy

    vercel
  3. Add Environment Variables

    • Go to Vercel Dashboard β†’ Settings β†’ Environment Variables
    • Add all variables from .env

MongoDB Atlas Setup

  1. Create a free account at MongoDB Atlas
  2. Create a new cluster
  3. Create database user and get connection string
  4. Update MONGODB_URI in environment variables

πŸ“š API Documentation

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

πŸ§ͺ Validation Rules

User Registration

  • name: 2-50 characters, required
  • email: Valid email format, required, unique
  • password: Minimum 6 characters, required

User Login

  • email: Valid email format, required
  • password: Required

Task Creation

  • title: 1-200 characters, required
  • completed: Boolean, optional (defaults to false)

Task Update

  • title: 1-200 characters, optional
  • completed: Boolean, optional
  • At least one field must be provided

πŸ› Error Handling

The API returns consistent error responses:

{
  "success": false,
  "data": null,
  "message": "Error description",
  "errors": [] // Array of validation errors (if applicable)
}

Common HTTP Status Codes

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request (validation error)
  • 401 - Unauthorized (not authenticated)
  • 403 - Forbidden (not authorized)
  • 404 - Not Found
  • 500 - Internal Server Error

πŸ“– Learning Resources


🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


πŸ“„ License

This project is licensed under the ISC License.


πŸ‘¨β€πŸ’» Author

Your Name


πŸ™ Acknowledgments

  • 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

Releases

Packages

Contributors

Languages