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.
- 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
/healthendpoint using@nestjs/terminusfor container orchestration platforms (like Kubernetes) and enables graceful shutdown hooks to prevent dropped requests during deployments. - Validation: Global
ValidationPipeconfigured withclass-validatorto automatically validate all incoming request DTOs. - Scalable Architecture: Employs a
CoreModuleto encapsulate infrastructure concerns, keeping the mainAppModuleclean and focused on orchestrating feature modules.
This template promotes a clean separation of concerns.
CoreModule: Located insrc/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 rootAppModule. HealthModule: A standalone module dedicated to exposing the application's health status for operational monitoring.
- Node.js (LTS version recommended)
- NPM or Yarn
- Docker and Docker Compose (for running a local PostgreSQL instance)
Clone the repository and install the project dependencies.
git clone <repository-url> your-project-name
cd your-project-name
npm installCreate a .env file in the project root by copying the example file.
cp .env.example .envReview the .env file and update the variables for your local environment, particularly the DATABASE_* values.
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 -dThis will start a PostgreSQL server in the background with the credentials specified in the docker-compose.yml file. Ensure these match your .env file.
Once the database is running, apply the initial migrations to create the necessary tables.
npm run migration:run-
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
| 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. |
This template is configured for a code-first, migration-based workflow. Never use synchronize: true in a production environment.
- Modify an Entity: Make changes to any TypeORM entity file (e.g., add a new column).
- Generate a Migration: Run the generation script with a descriptive name.
npm run migration:generate src/database/migrations/AddUserRole
- Review the Migration: Inspect the newly generated file in
src/database/migrations/to ensure the SQL is correct. - Run the Migration: Apply the changes to your database.
npm run migration:run