Skip to content

stubbies/nestjs-api-template

Repository files navigation

Production-Ready NestJS API Template

This repository serves as a starter template for building scalable, secure, and maintainable backend services using NestJS. It is pre-configured with a suite of production-grade tools and architectural patterns to accelerate development and ensure best practices from the start.

Core Features

  • High-Performance Server: Uses Fastify instead of Express for significantly better HTTP performance and lower overhead.
  • Optimized Build System: Integrated with the SWC (Speedy Web Compiler) for dramatically faster build and compilation times.
  • Robust Configuration: Centralized, environment-aware configuration using @nestjs/config. Includes schema validation with Joi to ensure all required environment variables are present and valid on startup.
  • Security Foundation:
    • Helmet: Sets crucial security-related HTTP headers to protect against common vulnerabilities.
    • CORS: Pre-configured Cross-Origin Resource Sharing for secure frontend integration.
    • Rate Limiting: Global request rate limiting to prevent abuse and brute-force attacks.
  • Structured Logging: Production-ready logging with Pino. Outputs colorized, human-readable logs in development and structured JSON logs in production for easy ingestion by log management systems.
  • Database & Migrations:
    • TypeORM: Integrated with TypeORM for robust database interaction with a PostgreSQL server.
    • Migration Support: A complete, script-based workflow for generating and running database schema migrations, ensuring safe and version-controlled database changes.
  • Health Checks & Graceful Shutdown: Implements a /health endpoint using @nestjs/terminus for container orchestration platforms (like Kubernetes) and enables graceful shutdown hooks to prevent dropped requests during deployments.
  • Validation: Global ValidationPipe configured with class-validator to automatically validate all incoming request DTOs.
  • Scalable Architecture: Employs a CoreModule to encapsulate infrastructure concerns, keeping the main AppModule clean and focused on orchestrating feature modules.

Architecture

This template promotes a clean separation of concerns.

  • CoreModule: Located in src/core, this global module is responsible for importing and configuring all application-wide, cross-cutting concerns such as configuration (ConfigModule), logging (LoggerModule), and the database connection (TypeOrmModule).
  • Feature Modules: Business logic should be organized into dedicated feature modules (e.g., UsersModule, ProductsModule). These modules should be imported into the root AppModule.
  • HealthModule: A standalone module dedicated to exposing the application's health status for operational monitoring.

Prerequisites

  • Node.js (LTS version recommended)
  • NPM or Yarn
  • Docker and Docker Compose (for running a local PostgreSQL instance)

Getting Started

1. Installation

Clone the repository and install the project dependencies.

git clone <repository-url> your-project-name
cd your-project-name
npm install

2. Environment Configuration

Create a .env file in the project root by copying the example file.

cp .env.example .env

Review the .env file and update the variables for your local environment, particularly the DATABASE_* values.

3. Database Setup

The simplest way to run a local PostgreSQL database is with Docker. A docker-compose.yml file is provided for this purpose.

Start the database container:

docker-compose up -d

This will start a PostgreSQL server in the background with the credentials specified in the docker-compose.yml file. Ensure these match your .env file.

4. Run Initial Database Migration

Once the database is running, apply the initial migrations to create the necessary tables.

npm run migration:run

Running the Application

  • Development Mode: Starts the application with hot-reloading.

    npm run start:dev
  • Production Build: Compiles the TypeScript source into JavaScript.

    npm run build
  • Production Mode: Runs the previously built application.

    npm run start:prod

Key Scripts

Script Description
start:dev Runs the application in watch mode using the SWC builder.
build Compiles the application for production.
start:prod Starts the production build of the application.
test Runs the Jest test suite.
lint Lints the codebase using ESLint.
migration:generate Generates a new migration file based on entity changes.
migration:run Executes all pending database migrations.
migration:revert Reverts the last executed migration.

Database Migrations Workflow

This template is configured for a code-first, migration-based workflow. Never use synchronize: true in a production environment.

  1. Modify an Entity: Make changes to any TypeORM entity file (e.g., add a new column).
  2. Generate a Migration: Run the generation script with a descriptive name.
    npm run migration:generate src/database/migrations/AddUserRole
  3. Review the Migration: Inspect the newly generated file in src/database/migrations/ to ensure the SQL is correct.
  4. Run the Migration: Apply the changes to your database.
    npm run migration:run

About

Starter template for building scalable, secure, and maintainable backend services using NestJS

Topics

Resources

License

Stars

Watchers

Forks