Skip to content

πŸš€ Starter Express.js API template with TypeScript and Mongoose for fast, scalable backend development

Notifications You must be signed in to change notification settings

vsmm-world/express-typescript-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

21 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Express Vercel API

A robust, scalable Express.js API with TypeScript, featuring a clean module-based architecture, user CRUD operations, and comprehensive authentication with validation.

Features

  • βœ… Module-Based Architecture - Clean, scalable, feature-based code organization
  • βœ… User CRUD Operations - Create, Read, Update, Delete users
  • βœ… JWT Authentication - Secure token-based authentication
  • βœ… Password Hashing - Bcrypt for secure password storage
  • βœ… Input Validation - Express-validator for request validation
  • βœ… Error Handling - Centralized error handling middleware
  • βœ… Role-Based Access Control - User and Admin roles
  • βœ… Rate Limiting - Protection against brute force attacks
  • βœ… Security Headers - Helmet.js for security
  • βœ… MongoDB Integration - Mongoose ODM
  • βœ… TypeScript - Full type safety
  • βœ… Vercel Ready - Serverless function deployment

Project Structure

express-api/
β”œβ”€ api/
β”‚  └─ index.ts                    # Vercel serverless entry point
β”œβ”€ src/
β”‚  β”œβ”€ modules/                    # Feature modules (self-contained)
β”‚  β”‚  β”œβ”€ auth/                    # Authentication module
β”‚  β”‚  β”‚  β”œβ”€ auth.controller.ts    # Auth request handlers
β”‚  β”‚  β”‚  β”œβ”€ auth.service.ts        # Auth business logic
β”‚  β”‚  β”‚  β”œβ”€ auth.routes.ts         # Auth route definitions
β”‚  β”‚  β”‚  β”œβ”€ auth.types.ts          # Auth-specific types/DTOs
β”‚  β”‚  β”‚  β”œβ”€ auth.validations.ts    # Auth validation rules
β”‚  β”‚  β”‚  └─ index.ts               # Module exports
β”‚  β”‚  β”‚
β”‚  β”‚  └─ user/                     # User management module
β”‚  β”‚     β”œβ”€ user.controller.ts     # User request handlers
β”‚  β”‚     β”œβ”€ user.service.ts        # User business logic
β”‚  β”‚     β”œβ”€ user.routes.ts         # User route definitions
β”‚  β”‚     β”œβ”€ user.types.ts          # User-specific types/DTOs
β”‚  β”‚     β”œβ”€ user.validations.ts    # User validation rules
β”‚  β”‚     └─ index.ts               # Module exports
β”‚  β”‚
β”‚  β”œβ”€ services/                    # Shared services
β”‚  β”‚  └─ jwt.service.ts            # JWT token operations
β”‚  β”‚
β”‚  β”œβ”€ middleware/                  # Express middleware
β”‚  β”‚  β”œβ”€ auth.middleware.ts        # JWT authentication middleware
β”‚  β”‚  β”œβ”€ error.middleware.ts       # Error handling middleware
β”‚  β”‚  └─ validation.middleware.ts  # Request validation middleware
β”‚  β”‚
β”‚  β”œβ”€ models/                      # Database models
β”‚  β”‚  └─ User.ts                   # User model/schema
β”‚  β”‚
β”‚  β”œβ”€ config/                      # Configuration files
β”‚  β”‚  └─ db.ts                     # Database configuration
β”‚  β”‚
β”‚  β”œβ”€ shared/                      # Shared utilities & constants
β”‚  β”‚  β”œβ”€ constants/
β”‚  β”‚  β”‚  └─ index.ts              # All constants (HTTP status, errors, etc.)
β”‚  β”‚  β”œβ”€ types/
β”‚  β”‚  β”‚  └─ index.ts              # Shared TypeScript types
β”‚  β”‚  β”œβ”€ helpers/
β”‚  β”‚  β”‚  β”œβ”€ response.helper.ts    # API response helpers
β”‚  β”‚  β”‚  └─ pagination.helper.ts   # Pagination utilities
β”‚  β”‚  └─ utils/
β”‚  β”‚     └─ logger.ts             # Logging utility
β”‚  β”‚
β”‚  β”œβ”€ views/                       # HTML views
β”‚  β”‚  └─ index.html                # API documentation page
β”‚  β”‚
β”‚  └─ app.ts                       # Express app setup
β”œβ”€ scripts/
β”‚  └─ copy-views.js                # Build script for copying views
β”œβ”€ vercel.json                     # Vercel configuration
└─ package.json

Architecture

Module-Based Structure

The project follows a module-based architecture where each feature is self-contained in its own module. Each module includes:

  • Controller - Handles HTTP requests and responses
  • Service - Contains business logic
  • Routes - Defines API endpoints
  • Types - Module-specific TypeScript interfaces and DTOs
  • Validations - Request validation rules
  • Index - Centralized exports for clean imports

Benefits

  • 🎯 Scalability - Easy to add new features without affecting existing code
  • πŸ”§ Maintainability - Related code is grouped together
  • πŸ§ͺ Testability - Modules can be tested independently
  • πŸ“¦ Reusability - Modules can be easily extracted or moved
  • 🎨 Clean Code - Clear separation of concerns

Adding a New Module

  1. Create a new folder in src/modules/[module-name]/
  2. Add the required files:
    • [module].controller.ts
    • [module].service.ts
    • [module].routes.ts
    • [module].types.ts
    • [module].validations.ts
    • index.ts
  3. Import and use in app.ts:
    import { moduleRoutes } from "./modules/[module-name]";
    app.use("/api/[module]", moduleRoutes);

Prerequisites

  • Node.js 18+
  • Yarn (recommended package manager)
  • MongoDB (local or cloud instance)

Install Yarn globally if you haven't already:

npm install -g yarn
# or
corepack enable

Installation

  1. Clone the repository
  2. Install dependencies:
yarn install
  1. Create a .env file based on .env.example:
cp .env.example .env
  1. Update the .env file with your configuration:
    • Set MONGODB_URI to your MongoDB connection string
    • Set JWT_SECRET to a strong random string
    • Configure other environment variables as needed

Development

Run the development server:

yarn dev

The server will start on http://localhost:8080 (or the port specified in .env).

Visit http://localhost:8080/ to see the beautiful API documentation page.

API Endpoints

Authentication

  • POST /api/auth/register - Register a new user
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user (requires authentication)

Users (All require authentication)

  • GET /api/users - Get all users (paginated)
    • Query params: ?page=1&limit=10
  • GET /api/users/:id - Get user by ID
  • POST /api/users - Create user (admin only)
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user (admin only, soft delete)

Health Check

  • GET /health - Server health check
  • GET / - API documentation page (HTML)

Request/Response Examples

Register User

Request:

POST /api/auth/register
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "Password123",
  "role": "user"
}

Response:

{
  "success": true,
  "data": {
    "user": {
      "id": "...",
      "name": "John Doe",
      "email": "john@example.com",
      "role": "user"
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

Login

Request:

POST /api/auth/login
{
  "email": "john@example.com",
  "password": "Password123"
}

Response:

{
  "success": true,
  "data": {
    "user": {
      "id": "...",
      "name": "John Doe",
      "email": "john@example.com",
      "role": "user"
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}

Get All Users

Request:

GET /api/users?page=1&limit=10
Headers: Authorization: Bearer <token>

Response:

{
  "success": true,
  "data": {
    "users": [...],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 50,
      "pages": 5
    }
  }
}

Authentication

All protected routes require a JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Validation Rules

Password Requirements

  • Minimum 6 characters
  • At least one uppercase letter
  • At least one lowercase letter
  • At least one number

Email

  • Must be a valid email format
  • Automatically normalized (lowercase, trimmed)

Name

  • 2-50 characters
  • Trimmed

Error Handling

All errors follow a consistent format:

{
  "success": false,
  "error": {
    "message": "Error message here"
  }
}

Validation errors include field-specific information:

{
  "success": false,
  "error": {
    "message": "Validation failed"
  },
  "data": {
    "errors": [
      {
        "field": "email",
        "message": "Please provide a valid email address"
      }
    ]
  }
}

Deployment to Vercel

  1. Install Vercel CLI:
yarn global add vercel
# or
npm i -g vercel
  1. Deploy:
vercel
  1. Set environment variables in Vercel dashboard:
    • MONGODB_URI
    • JWT_SECRET
    • CORS_ORIGIN
    • JWT_EXPIRES_IN

Scripts

  • yarn dev - Start development server
  • yarn build - Build for production (compiles TypeScript and copies views)
  • yarn start - Start production server
  • yarn vercel-build - Build for Vercel deployment
  • yarn vercel-dev - Run Vercel development server
  • yarn lint - Run ESLint
  • yarn type-check - Type check without building

Why Yarn?

This project uses Yarn as the package manager for several advantages:

  • ⚑ Fast & Reliable - Deterministic installs with lockfile
  • πŸ”’ Secure - Better security auditing and vulnerability detection
  • πŸ“¦ Workspaces - Excellent monorepo support
  • 🎯 Mature - Stable and widely adopted in production environments
  • πŸ”„ Offline Mode - Can work offline with cached packages

Code Organization

Shared Resources

The shared/ folder contains reusable utilities:

  • constants/ - HTTP status codes, error messages, default values
  • types/ - Shared TypeScript interfaces and types
  • helpers/ - Response helpers, pagination utilities
  • utils/ - Logging and other utilities

Services

The services/ folder contains shared services used across modules:

  • jwt.service.ts - JWT token generation and verification

Middleware

The middleware/ folder contains Express middleware:

  • auth.middleware.ts - JWT authentication
  • error.middleware.ts - Centralized error handling
  • validation.middleware.ts - Request validation

Security Features

  • Password hashing with bcrypt
  • JWT token authentication
  • Rate limiting (100 requests per 15 minutes per IP)
  • Helmet.js security headers
  • CORS configuration
  • Input validation and sanitization
  • Role-based access control
  • Soft delete for users

Technology Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Language: TypeScript
  • Database: MongoDB with Mongoose
  • Authentication: JWT (jsonwebtoken)
  • Validation: express-validator
  • Security: Helmet, bcryptjs, express-rate-limit
  • Deployment: Vercel (Serverless)

License

ISC

About

πŸš€ Starter Express.js API template with TypeScript and Mongoose for fast, scalable backend development

Topics

Resources

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •