/nestjs-starter-kit

Nest.js starter kit with Postgres, Redis, Docker, TypeORM, JWT auth, and more!

Primary LanguageTypeScript

Nest.js starter kit

test codecov

This is a starter kit for typical Nest.js REST API project.

Motivation

The main goal of this project is to provide fully functional Nest.js app which can be used as a started kit for creating your own REST APIs.

Usually it is not enough to just run $ nest new project and start writing required business logic. Nest.js provides a minimal application out of the box with only one controller and service. In most cases it is required to pull and setup a bunch of additional packages from Nest.js ecosystem like typeorm, passport, cache-manager, DTO validators etc.

This repo provides an already configured REST API project with commonly used Nest.js packages (full list below) so you can just copy it and start writing your business logic and not waste your time for boilerplate configuration.

Features

Dockerized local development

You are getting fully functional docker environment for development with Postgres DB, Redis and utility services such as local SMTP server. You can spin-up all server dependencies with only 1 command without need of setting up DB and Redis servers manually.

Check out .docker-node-api folder and installation guide for more details.

Configuration via ENV variables

According to 12 factor app - it is recommended to store application config in Environment Variables. This technique allows you to build the bundle once and deploy it to multiple target server (e.g. QA, Staging, Prod) without code modifications. Each target environment will have different configuration values which application retrieves from environment variables.

This project provides a set of config values out of the box e.g. for connecting to DB and Cache server. Check out app.module.ts and configuration.ts for more details.

Validation via DTO

Global ValidationPipeline enabled and requests to APIs are validated via DTOs.

DB migrations

TypeORM DB migrations are already set up for you in ./api/src/db/migrations folder.

To generate new migration run:

npm run migrations:new -- src/db/migrations/Roles

To apply migrations run:

npm run migrations:up

To revert migrations run:

npm run migrations:revert

Redis cache

cache-manager package with Redis store is available in app-cache.module.ts.

So it is possible to use CacheInterceptor above you controller methods or classes:

  @UseInterceptors(CacheInterceptor)
  @Get()
  async getUsers() {}

Or inject CacheManager and use it directly:

constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}

await this.cacheManager.set('test', 'test', {
  ttl: 10, // in seconds
} as any);

await this.cacheManager.get('key');

JWT auth with passport.js

JWT authentication is configured and available to use.

User registration, login and JWT-protected API examples were added in user.controller.ts

Logger with Trace ID generation

Pino added as application logger.

Each request to API is signed with unique TraceID and passed to logger via AsyncLocalStorage.

Code can be found in async-storage.middleware.ts and app-logger.service.ts

TraceID in logs example

Graceful shutdown

Nest.js shutdown hooks are enabled.

This starter kit subscribed to OnModuleDestroy event and disconnects from Redis gracefully.

Automatic APIs documentation with Swagger

Nest.js swagger module configured with the use of Swagger CLI plugin.

API docs are generated with the start of app server automatically and available at http://localhost:3000/api:

Swagger doc generated

E-mail service with local mail trap

Mail service is available out of the box and can be used like this:

Inject in constructor:

constructor(
  private readonly mailer: MailService,
) {}

Send mail:

await this.mailer.send({
  to: 'to-mail@example.com',
  from: this.mailer.from(),
  subject: 'User registered',
  text: 'Mail body',
});

You can check sent mails by opening http://localhost:8025/ and browse MailHog UI.

MailHog UI

Powered by nodemailer.

Unit tests

All code added in the project is covered with unit tests.

You can find useful tests examples of:

Health check

Health check endpoint is available at http://localhost:3000/health and returns 200 OK if server is healthy. This endpoint also checks DB and Redis connections.

Installation

Prerequisites

  • Docker for Desktop
  • Node.js LTS

Getting started

  • Clone the repository
git clone https://github.com/rodion-arr/nestjs-starter-kit.git
  • Run docker containers (DB, Redis, etc)
cd nestjs-starter-kit/.docker-node-api
docker-compose up -d
  • Go to api folder and copy env file
cd ../api
cp .env.example .env
  • Update .env file with credentials if needed

  • Next install dependencies

npm ci
  • Init config and run migrations
npm run migrations:up
  • Run application
npm start