Skip to content

Repository files navigation

Express TypeScript REST API Boilerplate

TypeScript Badge Express.js Badge JWT Badge ESLint Badge Prettier Badge Nodemon Badge Helmet Badge CORS Badge

A production-ready Express.js REST API boilerplate built with TypeScript, featuring JWT authentication, comprehensive middleware, and scalable architecture.

🚀 Features

  • TypeScript - Full type safety and modern JavaScript features
  • Express.js 5 - Fast, unopinionated web framework
  • JWT Authentication - Access and refresh token implementation
  • Security First - Helmet, CORS, rate limiting, and input validation
  • Error Handling - Centralized error handling with custom error types
  • Validation - Express-validator for request validation
  • Development Tools - ESLint, Prettier, Nodemon, and TSX for hot reloading
  • ES Modules - Modern module system support
  • Environment Configuration - Flexible configuration management
  • Logging - Structured logging system
  • Middleware Stack - Comprehensive middleware setup

📦 Tech Stack

Core Dependencies

  • express (v5.1.0) - Web framework
  • typescript (v5.9.2) - Type safety
  • jsonwebtoken (v9.0.2) - JWT authentication
  • dotenv (v17.2.1) - Environment variables
  • express-validator (v7.2.1) - Input validation

Security & Middleware

  • helmet (v8.1.0) - Security headers
  • cors (v2.8.5) - Cross-origin resource sharing
  • express-rate-limit (v8.0.1) - Rate limiting
  • cookie-parser (v1.4.7) - Cookie parsing

Development Tools

  • nodemon (v3.1.10) - Development server
  • tsx (v4.20.5) - TypeScript execution
  • eslint (v9.34.0) - Code linting
  • prettier (v3.6.2) - Code formatting
  • typescript-eslint (v8.41.0) - TypeScript ESLint rules

📁 Project Structure

src/
├── config/                # Configuration management
│   └── config.ts          # Environment variables and app config
├── middlewares/           # Express middleware
│   ├── auth.middleware.ts # JWT authentication middleware
│   ├── error.middleware.ts# Global error handling
│   ├── log.middleware.ts  # Request logging
│   └── httpMethods.middleware.ts # HTTP method restrictions
├── services/              # Business logic layer
│   └── webserver.ts       # Express server setup and configuration
├── utils/                 # Utility functions
│   ├── constants.ts       # Application constants
│   └── tokens.ts          # JWT token management
├── validators/            # Request validation
│   └── auth.validator.ts  # Authentication validation rules
├── types/                 # TypeScript type definitions
│   └── index.ts           # Shared interfaces and types
├── controllers/           # Request handlers (to be implemented)
├── routes/                # Route definitions (to be implemented)
└── server.ts              # Application entry point

Root Files:
├── .env.example           # Environment variables template
├── .gitignore             # Git ignore rules
├── eslint.config.mts      # ESLint configuration
├── nodemon.json           # Nodemon configuration
├── package.json           # Dependencies and scripts
├── tsconfig.json          # TypeScript configuration
└── README.md              # Project documentation

🛠️ Quick Start

Prerequisites

  • Node.js (v18+ recommended)
  • npm

Installation

  1. Clone the repository

    git clone https://github.com/mar1shell/express-nodejs-boilerplate.git
    cd express-nodejs-boilerplate
  2. Install dependencies

    npm install
  3. Configure your .env file

    NODE_ENV=development
    RESOURCE_PORT=3000
    AUTH_PORT=3001
    JWT_SECRET_KEY=your-super-secret-jwt-key
    JWT_REFRESH_SECRET_KEY=your-super-secret-refresh-key
    CORS_ORIGIN=http://localhost:3000
  4. Start development server

    npm run dev

📝 Available Scripts

# Development
npm run dev          # Start development server with hot reload
npm run build        # Build TypeScript to JavaScript
npm run start        # Start production server

# Code Quality
npm run lint         # Run ESLint
npm run lint:fix     # Fix ESLint errors automatically

🔧 Core Features

JWT Authentication

Complete JWT implementation with access and refresh tokens:

// Generate tokens
const accessToken = generateAccessToken({ id: userId, email });
const refreshToken = generateRefreshToken({ id: userId });

// Verify tokens
const payload = verifyAccessToken(token);

// Extract from requests
const token = extractAccessToken(req);

Middleware Stack

Comprehensive middleware setup including:

  • Security: Helmet for security headers
  • CORS: Configurable cross-origin requests
  • Rate Limiting: Protection against abuse
  • Validation: Express-validator integration
  • Error Handling: Centralized error management
  • Logging: Request/response logging

Input Validation

Express-validator integration with custom error formatting:

// Example validator
export const loginValidator = [
  body("email").isEmail().withMessage("Valid email required"),
  body("password").notEmpty().withMessage("Password required"),
  handleValidationErrors,
];

🏗️ Architecture

Modular Design

  • Separation of Concerns: Clear separation between routes, controllers, services, and utilities
  • Middleware Pattern: Reusable middleware for common functionality
  • Type Safety: Full TypeScript integration with proper typing
  • Configuration Management: Environment-based configuration

Scalability Features

  • Class-based Server: Object-oriented server architecture
  • Utility Functions: Reusable utility functions
  • Custom Error Types: Structured error handling
  • Validation Layer: Comprehensive input validation

🔒 Security Features

  • Helmet: Security headers configuration
  • CORS: Cross-origin request handling
  • Rate Limiting: Request rate limiting
  • JWT Security: Secure token implementation
  • Input Validation: Request data validation
  • Error Sanitization: Safe error responses

🌐 Environment Configuration

The boilerplate uses environment variables for configuration:

# Server Configuration
NODE_ENV=development
RESOURCE_PORT=3000
AUTH_PORT=3001

# JWT Configuration
JWT_SECRET_KEY=your-secret-key
JWT_REFRESH_SECRET_KEY=your-refresh-secret

# CORS Configuration
CORS_ORIGIN=http://localhost:3000
CORS_CREDENTIALS=true

🧪 Usage Guidelines

Adding New Routes

  1. Create route files in src/routes/
  2. Implement controllers in src/controllers/
  3. Add validation in src/validators/
  4. Register routes in your main router

Implementing Business Logic

  1. Create services in src/services/
  2. Add database models (when implementing DB layer)
  3. Use middleware for cross-cutting concerns

Error Handling

  • Use custom error classes for different scenarios
  • All errors are automatically handled by the error middleware
  • Maintain consistent error response format

🔄 Next Steps

This boilerplate provides a solid foundation. Consider adding:

  • Database Integration (MongoDB, PostgreSQL, etc.)
  • Testing Suite (Jest, Supertest)
  • API Documentation (Swagger/OpenAPI)
  • Docker Configuration
  • CI/CD Pipeline
  • Monitoring & Metrics

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
    git checkout -b feature/my-feature
  3. Commit changes using conventional commits
    git commit -m "feat: add new feature"
  4. Push to branch
    git push origin feature/my-feature
  5. Open a Pull Request

📏 Commit Guidelines

We use Conventional Commits:

  • feat: → New features
  • fix: → Bug fixes
  • docs: → Documentation updates
  • style: → Code formatting
  • refactor: → Code refactoring
  • test: → Testing updates
  • chore: → Maintenance tasks

📜 License

This project is licensed under the MIT License.


Made with ❤️ by Your Name

About

Express.js + Node.js boilerplate — Rest API, JWT auth, CRUD setup, and scalable modular architecture.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages