Skip to content

ebukaodini/express-api-template

Repository files navigation

Express TypeScript API Template

A robust, production-ready Express.js API template built with TypeScript, featuring comprehensive testing, documentation, and modern development practices.

πŸš€ Features

  • TypeScript - Full type safety and modern JavaScript features
  • Express.js - Fast, unopinionated web framework
  • Central Entry Point - Robust application architecture with dependency injection
  • Prisma - Modern database toolkit with type-safe queries
  • Jest - Comprehensive testing suite with unit and integration tests
  • Swagger/OpenAPI - Interactive API documentation
  • Winston - Structured logging
  • Rate Limiting - Built-in request rate limiting
  • Security - Helmet.js for security headers
  • Validation - Class-validator for request validation
  • Error Handling - Custom error classes and centralized error handling
  • Environment Configuration - Centralized config management
  • Docker Support - Ready for containerization
  • Code Quality - Prettier, ESLint, and TypeScript strict mode

πŸ“ Project Structure

src/
β”œβ”€β”€ app/                   # Central entry point architecture
β”‚   β”œβ”€β”€ application.ts      # Main application class
β”‚   └── service-registry.ts # Service management
β”œβ”€β”€ bootstrap/                 # Configuration management
β”‚   β”œβ”€β”€ app.ts      # Express app setup
β”‚   β”œβ”€β”€ config.ts      # Main application class
β”‚   β”œβ”€β”€ errors.ts      # Custom error classes
β”‚   β”œβ”€β”€ modules.ts      # Main application class
β”‚   β”œβ”€β”€ seeders.ts      # Main application class
β”‚   └── services.ts      # Main application class
β”œβ”€β”€ features/               # Feature-based modules
β”‚   └── user/              # User feature module
β”‚       β”œβ”€β”€ user.controller.ts
β”‚       β”œβ”€β”€ user.service.ts
β”‚       β”œβ”€β”€ user.repo.ts
β”‚       β”œβ”€β”€ user.dto.ts
β”‚       └── user.entity.ts
β”œβ”€β”€ middlewares/            # Express middlewares
β”œβ”€β”€ services/               # Shared services
β”œβ”€β”€ utils/                  # Utility functions
β”œβ”€β”€ server.ts                 # Central entry point
β”œβ”€β”€ __tests__/             # Test files
β”‚   β”œβ”€β”€ unit/              # Unit tests
β”‚   β”œβ”€β”€ integration/       # Integration tests
β”‚   └── prisma.config.ts          # Test configuration

πŸ› οΈ Setup

Prerequisites

  • Node.js (v18 or higher)
  • PostgreSQL (v12 or higher)
  • npm or yarn

1. Clone the repository

npx degit https://github.com/ebukaodini/express-api-template.git my-api
cd my-api

2. Install dependencies

pnpm install

3. Environment Configuration

Create a .env file in the root directory:

cp .env.example .env

Update the environment variables:

# Server Configuration
PORT=3000
NODE_ENV=development

# Database Configuration
DATABASE_URL="postgresql://username:password@localhost:5432/sample_api"

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

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX=100

# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="24h"

# Logging
LOG_LEVEL="debug"

4. Database Setup

# Generate Prisma client
pnpm prisma:generate

# Run database migrations
pnpm prisma:migrate

# Seed the database (optional)
pnpm seed:dev

5. Start the development server

Traditional way:

pnpm dev

The API will be available at http://localhost:3000

πŸ“š API Documentation

Once the server is running, you can access the interactive API documentation at:

  • Swagger UI: http://localhost:3000/api-docs
  • Health Check: http://localhost:3000/health

πŸ§ͺ Testing

Run all tests

pnpm test

Run tests in watch mode

pnpm run test:watch

Run tests with coverage

npm run test:coverage

Run integration tests only

npm run test:integration

πŸ“ Available Scripts

Script Description
npm run dev Start development server with hot reload
npm run build Build the project for production
npm start Start production server
npm test Run all tests
npm run test:watch Run tests in watch mode
npm run test:coverage Run tests with coverage report
npm run test:integration Run integration tests only
npm run test:central Run central entry point tests
npm run example Run central entry point examples
npm run start:central Start with central entry point
npm run dev:central Development with central entry point
npm run lint Format code with Prettier
npm run lint:check Check code formatting
npm run prisma:migrate Run database migrations
npm run prisma:generate Generate Prisma client
npm run prisma:seed Seed the database
npm run docs Display API documentation info

πŸ—οΈ Architecture

Central Entry Point Architecture

This template implements a robust central entry point architecture that provides:

  • Application Class - Main orchestrator for application lifecycle
  • Dependency Injection - Container-based service management
  • Service Registry - Centralized service lifecycle management
  • Service Factory - Factory pattern for service creation
  • Health Monitoring - Comprehensive service health checks

Feature-Based Structure

The project follows a feature-based architecture where each feature is self-contained with its own:

  • Controller - Handles HTTP requests and responses
  • Service - Contains business logic
  • Repository - Handles data access
  • DTO - Data transfer objects for validation
  • Entity - Domain models
  • Routes - API route definitions

Error Handling

  • Custom error classes for different error types
  • Centralized error handling middleware
  • Structured error responses
  • Proper HTTP status codes

Logging

  • Winston logger with multiple transports
  • Structured logging with timestamps
  • Different log levels for different environments
  • Request/response logging

Security

  • Helmet.js for security headers
  • CORS configuration
  • Rate limiting
  • Input validation
  • SQL injection protection (via Prisma)

πŸš€ Deployment

Docker

# Build the Docker image
docker build -t my-api .

# Run the container
docker run -p 3000:3000 my-api

Environment Variables for Production

Make sure to set the following environment variables in production:

  • NODE_ENV=production
  • DATABASE_URL - Your production database URL
  • JWT_SECRET - A strong, random secret key
  • CORS_ORIGIN - Your production frontend URL
  • LOG_LEVEL=info

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for your changes
  5. Ensure all tests pass
  6. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Built with scaffold.js
  • Inspired by modern Node.js best practices
  • Community contributions and feedback

About

An express typescript api template

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages