Skip to content

JomsCode21/Bare-Minimum-Planner-Back-End

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”§ Bare Minimum Planner - Backend

Secure & Scalable REST API for Task Management

Node.js TypeScript Express.js MongoDB

Features β€’ Tech Stack β€’ Getting Started β€’ API Docs β€’ Structure


✨ Features

πŸ” Authentication & Security

  • βœ… JWT-based authentication
  • βœ… Secure password hashing (bcrypt)
  • βœ… Token-based session management
  • βœ… Protected route middleware
  • βœ… Cookie-based auth tokens
  • βœ… Email verification support

πŸ›‘οΈ Security Measures

  • βœ… Rate limiting (prevents abuse)
  • βœ… Helmet.js (secure HTTP headers)
  • βœ… CORS configuration
  • βœ… MongoDB injection prevention
  • βœ… Input validation & sanitization

πŸ“ Task Management

  • βœ… Create, read, update, delete tasks
  • βœ… User-specific task ownership
  • βœ… Task completion tracking
  • βœ… Timestamp management
  • βœ… Task filtering by user

πŸ“§ Email Services

  • βœ… Password reset emails
  • βœ… Welcome emails
  • βœ… Nodemailer integration
  • βœ… HTML email templates
  • βœ… Email verification

πŸ› οΈ Tech Stack

Core Technologies

Node.js

Runtime

JavaScript runtime built on Chrome's V8 engine

Express

Framework

Fast, minimalist web framework for Node.js

MongoDB

Database

NoSQL database with Mongoose ODM

TypeScript

Language

Typed superset of JavaScript

πŸ“¦ Dependencies

Production Dependencies

Package Version Purpose
express 5.2.1 Web application framework
mongoose 9.2.0 MongoDB object modeling
jsonwebtoken 9.0.3 JWT authentication
bcrypt 6.0.0 Password hashing
cors 2.8.6 Cross-origin resource sharing
helmet 8.1.0 Security HTTP headers
express-rate-limit 8.2.1 Rate limiting middleware
nodemailer 8.0.1 Email sending
cookie-parser 1.4.7 Parse cookie headers
morgan 1.10.1 HTTP request logger
dotenv 17.3.1 Environment variables
moment 2.30.1 Date/time manipulation

Development Dependencies

Package Version Purpose
typescript 5.9.3 TypeScript compiler
tsx 4.21.0 TypeScript execution & watch
@types/* Latest TypeScript type definitions

πŸš€ Getting Started

Prerequisites

Ensure you have the following installed:

Node.js >= 18.x
npm >= 9.x
MongoDB (local or Atlas)

Installation

  1. Clone the repository
git clone https://github.com/JomsCode21/Bare-Minimum-Planner-Back-End.git
cd Bare-Minimum-Planner-Back-End
  1. Install dependencies
npm install
  1. Configure environment variables

Create a .env file in the root directory:

# Server Configuration
PORT=5000
NODE_ENV=development

# Database
MONGODB_URI=mongodb://localhost:27017/bare-minimum-planner
# OR for MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/bare-minimum-planner

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_here_minimum_32_characters
JWT_EXPIRES_IN=7d

# Email Configuration (Gmail example)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-specific-password
EMAIL_FROM=Bare Minimum Planner <noreply@bareminimumplanner.com>

# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:5173

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
  1. Start the development server
npm run dev

The server will start on http://localhost:5000 πŸš€


πŸ“ Project Structure

backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/                   # Configuration files
β”‚   β”‚   └── mail.config.ts        # Email configuration
β”‚   β”‚
β”‚   β”œβ”€β”€ controllers/              # Route controllers (business logic)
β”‚   β”‚   β”œβ”€β”€ task.controller.ts    # Task CRUD operations
β”‚   β”‚   └── user.controller.ts    # User authentication & management
β”‚   β”‚
β”‚   β”œβ”€β”€ db/                       # Database connection
β”‚   β”‚   └── index.ts              # MongoDB connection setup
β”‚   β”‚
β”‚   β”œβ”€β”€ middlewares/              # Custom middleware functions
β”‚   β”‚   β”œβ”€β”€ global-error-handler.middleware.ts
β”‚   β”‚   β”œβ”€β”€ limiter.middleware.ts              # Rate limiting
β”‚   β”‚   └── verify-token.middleware.ts         # JWT authentication
β”‚   β”‚
β”‚   β”œβ”€β”€ models/                   # Mongoose models (schemas)
β”‚   β”‚   β”œβ”€β”€ task.models.ts        # Task schema & model
β”‚   β”‚   └── user.model.ts         # User schema & model
β”‚   β”‚
β”‚   β”œβ”€β”€ routes/                   # API route definitions
β”‚   β”‚   β”œβ”€β”€ taskRoutes.ts         # Task endpoints
β”‚   β”‚   └── userRoutes.ts         # User & auth endpoints
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/                    # Utility functions
β”‚   β”‚   β”œβ”€β”€ mail.ts               # Email sending utilities
β”‚   β”‚   β”œβ”€β”€ ForgotPassword.ts     # Password reset logic
β”‚   β”‚   └── error/
β”‚   β”‚       └── app-error.util.ts # Custom error handler
β”‚   β”‚
β”‚   └── index.ts                  # Application entry point
β”‚
β”œβ”€β”€ .env                          # Environment variables (not in git)
β”œβ”€β”€ .env.example                  # Environment template
β”œβ”€β”€ .gitignore                    # Git ignore rules
β”œβ”€β”€ package.json                  # Dependencies & scripts
β”œβ”€β”€ tsconfig.json                 # TypeScript configuration
└── README.md                     # This file

πŸ“‘ API Documentation

Base URL

http://localhost:5000/api

πŸ” Authentication Endpoints

Method Endpoint Description Auth Required
POST /users/register Register a new user account ❌ No
POST /users/login Login with email and password ❌ No
POST /users/logout Logout current user βœ… Yes
GET /users/check-auth Verify authentication status βœ… Yes
POST /users/check-email Check if email exists ❌ No
POST /users/forgotpassword Request password reset email ❌ No
PUT /users/:id Update user information βœ… Yes
GET /users/ Get all users (admin) ❌ No

πŸ“ Task Endpoints

Method Endpoint Description Auth Required
GET /tasks Get all tasks for authenticated user βœ… Yes
POST /tasks Create a new task βœ… Yes
PUT /tasks/:id Update a specific task βœ… Yes
DELETE /tasks/:id Delete a specific task βœ… Yes

πŸ“‹ API Request/Response Examples

Register User

Request:

POST /api/users/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePassword123!"
}

Response (201 Created):

{
  "success": true,
  "message": "User registered successfully",
  "user": {
    "id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Login

Request:

POST /api/users/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "SecurePassword123!"
}

Response (200 OK):

{
  "success": true,
  "message": "Login successful",
  "user": {
    "id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Create Task

Request:

POST /api/tasks
Content-Type: application/json
Authorization: Bearer <jwt_token>

{
  "title": "Complete project documentation",
  "description": "Write comprehensive README files",
  "isCompleted": false
}

Response (201 Created):

{
  "success": true,
  "message": "Task created successfully",
  "task": {
    "id": "507f191e810c19729de860ea",
    "title": "Complete project documentation",
    "description": "Write comprehensive README files",
    "isCompleted": false,
    "userId": "507f1f77bcf86cd799439011",
    "createdAt": "2026-02-19T10:30:00.000Z",
    "updatedAt": "2026-02-19T10:30:00.000Z"
  }
}

Get All Tasks

Request:

GET /api/tasks
Authorization: Bearer <jwt_token>

Response (200 OK):

{
  "success": true,
  "count": 3,
  "tasks": [
    {
      "id": "507f191e810c19729de860ea",
      "title": "Complete project documentation",
      "description": "Write comprehensive README files",
      "isCompleted": false,
      "createdAt": "2026-02-19T10:30:00.000Z"
    }
    // ... more tasks
  ]
}

πŸ”’ Authentication Flow

sequenceDiagram
    participant Client
    participant API
    participant Database
    participant JWT

    Client->>API: POST /users/register
    API->>Database: Create User
    Database-->>API: User Created
    API->>JWT: Generate Token
    JWT-->>API: JWT Token
    API-->>Client: User Data + Token (Cookie)

    Client->>API: POST /users/login
    API->>Database: Verify Credentials
    Database-->>API: User Found
    API->>JWT: Generate Token
    JWT-->>API: JWT Token
    API-->>Client: User Data + Token (Cookie)

    Client->>API: GET /tasks (with token)
    API->>JWT: Verify Token
    JWT-->>API: Token Valid
    API->>Database: Fetch Tasks
    Database-->>API: Tasks Data
    API-->>Client: Tasks Response
Loading

πŸ›‘οΈ Security Features

Password Security

// Passwords are hashed using bcrypt with salt rounds
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

JWT Authentication

// JWT tokens are signed and verified with a secret key
const token = jwt.sign({ userId: user._id }, JWT_SECRET, {
  expiresIn: "7d",
});

Rate Limiting

// Prevents brute force attacks
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: "Too many requests from this IP",
});

Security Headers (Helmet)

  • Content Security Policy
  • X-Frame-Options
  • X-Content-Type-Options
  • Strict-Transport-Security
  • X-Download-Options
  • X-DNS-Prefetch-Control

πŸ“ Available Scripts

Command Description
npm run dev πŸ”₯ Start development server with hot reload and auto-restart
npm run typecheck πŸ” Run TypeScript type checking without emitting files

Development Workflow

# Start development server
npm run dev

# The server will:
# βœ… Watch for file changes
# βœ… Auto-reload on changes
# βœ… Load environment variables from .env
# βœ… Show detailed error messages
# βœ… Log all HTTP requests (morgan)

πŸ—„οΈ Database Models

User Model

{
  name: String (required),
  email: String (required, unique),
  password: String (required, hashed),
  createdAt: Date,
  updatedAt: Date
}

Task Model

{
  title: String (required),
  description: String,
  isCompleted: Boolean (default: false),
  userId: ObjectId (ref: 'User', required),
  createdAt: Date,
  updatedAt: Date
}

πŸ”§ Configuration

MongoDB Connection

The application automatically connects to MongoDB on startup:

// Local MongoDB
mongodb://localhost:27017/bare-minimum-planner

// MongoDB Atlas
mongodb+srv://<username>:<password>@cluster.mongodb.net/bare-minimum-planner

CORS Configuration

cors({
  origin: "http://localhost:5173", // Frontend URL
  credentials: true, // Allow cookies
});

Environment Variables

Variable Required Default Description
PORT No 5000 Server port
MONGODB_URI Yes - MongoDB connection string
JWT_SECRET Yes - Secret key for JWT signing
JWT_EXPIRES_IN No 7d JWT expiration time
EMAIL_HOST Yes - SMTP host
EMAIL_PORT Yes - SMTP port
EMAIL_USER Yes - Email account
EMAIL_PASSWORD Yes - Email password/app password
FRONTEND_URL Yes - Frontend application URL

πŸ› Error Handling

The API uses a global error handler that returns consistent error responses:

{
  "success": false,
  "error": {
    "message": "Error description",
    "statusCode": 400,
    "stack": "Error stack trace (development only)"
  }
}

Common HTTP Status Codes

Code Meaning
200 Success
201 Created
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict (e.g., email already exists)
429 Too Many Requests (rate limit)
500 Internal Server Error

πŸ§ͺ Testing

Manual API Testing

You can test the API using tools like:

  • Postman - Download
  • Insomnia - Download
  • Thunder Client - VS Code Extension
  • cURL - Command line

Example cURL Request

# Register a new user
curl -X POST http://localhost:5000/api/users/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "SecurePassword123!"
  }'

# Login
curl -X POST http://localhost:5000/api/users/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "SecurePassword123!"
  }'

# Create a task (with auth token)
curl -X POST http://localhost:5000/api/tasks \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "title": "Test Task",
    "description": "Task description"
  }'

πŸš€ Deployment

Prerequisites for Production

  • Node.js hosting (Heroku, Railway, Render, DigitalOcean, AWS, etc.)
  • MongoDB Atlas (cloud database)
  • Environment variables configured on hosting platform

Environment Setup

  1. Set up MongoDB Atlas

    • Create a free cluster at MongoDB Atlas
    • Get your connection string
    • Whitelist your application's IP
  2. Configure Environment Variables

    • Set all required .env variables on your hosting platform
    • Use production-grade secrets for JWT_SECRET
    • Update FRONTEND_URL to your production domain
  3. Deploy

# Build TypeScript (if needed)
npm run build

# Start production server
npm start

Deployment Platforms

Railway

Deploy on Railway

Fast, easy deployment with built-in PostgreSQL/MongoDB support

Render

Deploy to Render

Free tier available with automatic HTTPS

Heroku

Deploy to Heroku

Classic PaaS with extensive add-ons


πŸ” Troubleshooting

Server won't start
# Check if port is already in use
netstat -ano | findstr :5000  # Windows
lsof -i :5000                  # macOS/Linux

# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install
Database connection failed
  1. Verify MongoDB is running (local):
# Windows
net start MongoDB

# macOS/Linux
sudo systemctl start mongod
  1. Check connection string format
  2. Verify network access (MongoDB Atlas)
  3. Check firewall settings
JWT authentication errors
  1. Ensure JWT_SECRET is set in .env
  2. Check token expiration time
  3. Verify Authorization header format: Bearer <token>
  4. Clear cookies and login again
Email not sending
  1. Verify SMTP credentials
  2. For Gmail: Enable "Less secure app access" or use App Password
  3. Check email service provider's sending limits
  4. Verify network connectivity
CORS errors
  1. Verify FRONTEND_URL matches exactly
  2. Include trailing slash if necessary
  3. Check credentials configuration
  4. Ensure frontend sends credentials

πŸ“š Additional Resources

Documentation

Learning Resources


🀝 Contributing

We welcome contributions! Here's how you can help:

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch
    git checkout -b feature/amazing-feature
  3. ✍️ Commit your changes
    git commit -m 'Add some amazing feature'
  4. πŸ“€ Push to the branch
    git push origin feature/amazing-feature
  5. πŸ”ƒ Open a Pull Request

Contribution Guidelines

  • Write clear, descriptive commit messages
  • Follow existing code style and patterns
  • Add comments for complex logic
  • Test your changes thoroughly
  • Update documentation as needed

πŸ“„ License

This project is licensed under the ISC License.


πŸ‘₯ Team

JomsCode21
JomsCode21

πŸ”§ πŸ’» πŸ“–

πŸ™ Acknowledgments

  • πŸ’š Express.js Team - For the robust web framework
  • πŸƒ MongoDB Team - For the flexible NoSQL database
  • πŸ”’ Node.js Security Community - For security best practices
  • πŸ“§ Nodemailer Team - For email functionality
  • 🌟 Open Source Community - For amazing packages and support

πŸ”— Related Projects


⭐ Star this repo if you find it helpful!

Built with πŸ’™ and β˜• by the Bare Minimum Planner Team

⬆ Back to Top

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors