Home

Awesome

NestJS v10 Webpack Boilerplate

Banner

Language License Version

šŸ”„ Features

āš ļø Attention

Although there are advantages to use Webpack bundling your code (especially for serverless applications), there are some constraints, and details here (UPDATE: Both examples stated by the NestJS creator have already unblinded the native driver and are good to use now). Therefore, please make sure your application does not contain native bindings library, then you can enjoy the benefits.

Extra Configuration for Dependency Packages

Bull

You should install copy-webpack-plugin and copy bull default commands to the output directory when building the code.

pnpm install -D copy-webpack-plugin
// webpack.config.js;
const CopyWebpackPlugin = require('copy-webpack-plugin');
// ...
module.exports = {
  plugins: [
    // ...
    new CopyWebpackPlugin({
      patterns: [
        {
          context: 'node_modules/bull/lib/commands',
          from: '**/*.lua',
        },
      ],
    }),
  ];
}

Pino Pretty

By default we assume the application will run in production mode after building the app, so if you still using development mode you will get the error since you enable pino-pretty and it does not include in the production bundle. Therefore, if you want to use pino-pretty after bundling for any reason, you should install the pino-webpack-plugin.

pnpm install -D pino-webpack-plugin
// webpack.config.js
const { PinoWebpackPlugin } = require('pino-webpack-plugin');
// ...
module.exports = {
  // ...
  plugins: [
    // ...
    new PinoWebpackPlugin({ transports: ['pino-pretty'] }),
  ],
};

šŸ““ Commands

Commands Description

# build the app
$ pnpm build

# format the code
$ pnpm lint

# start the app
$ pnpm start

# run in development mode
$ pnpm start:dev || pnpm dev

# build the app and run it in production mode
$ pnpm start:prod || pnpm prod

# generate Swagger JSON schema
$ pnpm swagger

# test both unit test and e2e test
$ pnpm test

# test all the e2e test
$ pnpm test:e2e

# test all the unit test
$ pnpm test:unit

Running Application for Development

$ git clone <repo>

$ pnpm install

# Fill in require information in .env file
$ cp .env.example .env

# Linux / Mac users may require (allow git hook script executable)
$ chmod +x .husky -R

$ pnpm dev

šŸ“ Boilerplate Structure

ā”œā”€ā”€ ci
ā”‚   ā”œā”€ā”€ docker-compose.yaml
ā”‚   ā””ā”€ā”€ Dockerfile
ā”œā”€ā”€ .husky
ā”‚   ā”œā”€ā”€ _
ā”‚   ā”‚   ā”œā”€ā”€ .gitignore
ā”‚   ā”‚   ā””ā”€ā”€ husky.sh
ā”‚   ā”œā”€ā”€ commit-msg
ā”‚   ā”œā”€ā”€ pre-commit
ā”‚   ā””ā”€ā”€ pre-push
ā”œā”€ā”€ src
ā”‚   ā”œā”€ā”€ exception
ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā””ā”€ā”€ normal.exception.ts
ā”‚   ā”œā”€ā”€ filter
ā”‚   ā”‚   ā”œā”€ā”€ all-exception.filter.ts
ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā”œā”€ā”€ normal-exception.filter.ts
ā”‚   ā”‚   ā””ā”€ā”€ validator-exception.filter.ts
ā”‚   ā”œā”€ā”€ interceptor
ā”‚   ā”‚   ā””ā”€ā”€ response.interceptor.ts
ā”‚   ā”œā”€ā”€ modules
ā”‚   ā”‚   ā”œā”€ā”€ app
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ dto
ā”‚   ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ response
ā”‚   ā”‚   ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ version.dto.ts
ā”‚   ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ index.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ app.config.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ app.controller.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ app.module.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ app.service.spec.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ app.service.ts
ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ index.ts
ā”‚   ā”‚   ā””ā”€ā”€ http
ā”‚   ā”‚       ā”œā”€ā”€ http.module.ts
ā”‚   ā”‚       ā””ā”€ā”€ http.service.ts
ā”‚   ā”œā”€ā”€ shared
ā”‚   ā”‚   ā”œā”€ā”€ enums
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ log-level.ts
ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ node-env.ts
ā”‚   ā”‚   ā”œā”€ā”€ interfaces
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ response.ts
ā”‚   ā”‚   ā””ā”€ā”€ constants.ts
ā”‚   ā”œā”€ā”€ utils
ā”‚   ā”‚   ā”œā”€ā”€ clustering.ts
ā”‚   ā”‚   ā”œā”€ā”€ helper.ts
ā”‚   ā”‚   ā””ā”€ā”€ swagger.ts
ā”‚   ā”œā”€ā”€ env.d.ts
ā”‚   ā””ā”€ā”€ main.ts
ā”œā”€ā”€ test
ā”‚   ā”œā”€ā”€ app.e2e-spec.ts
ā”‚   ā”œā”€ā”€ common.ts
ā”‚   ā””ā”€ā”€ jest.e2e.config.ts
ā”œā”€ā”€ .vscode
ā”‚   ā”œā”€ā”€ extensions.json
ā”‚   ā””ā”€ā”€ settings.json
ā”œā”€ā”€ .commitlintrc.js
ā”œā”€ā”€ .dockerignore
ā”œā”€ā”€ .editorconfig
ā”œā”€ā”€ .env.example
ā”œā”€ā”€ .eslintignore
ā”œā”€ā”€ .eslintrc.js
ā”œā”€ā”€ .gitattributes
ā”œā”€ā”€ .gitignore
ā”œā”€ā”€ jest.config.ts
ā”œā”€ā”€ .lintstagedrc.js
ā”œā”€ā”€ nest-cli.json
ā”œā”€ā”€ .npmrc
ā”œā”€ā”€ package.json
ā”œā”€ā”€ pnpm-lock.yaml
ā”œā”€ā”€ .prettierrc.js
ā”œā”€ā”€ README.md
ā”œā”€ā”€ tsconfig.json
ā””ā”€ā”€ webpack.config.js

ā­ Coding Quality Tools Details Description

ESLint

It statically analyzes your code to help you detect formatting issues and find code inconsistencies, here we extend the ESLint TypeScript recommend rules, the most popular JavaScript style Airbnb, auto import sorting and shaking plugins.

# Config File
ā”œā”€ā”€ .eslintignore
ā””ā”€ā”€ .eslintrc.js

Prettier

Similar to ESLint, but mainly focus on auto-formatting, not the code quality. Actually, ESLint can do all the jobs that Prettier can do, but for the formatting part, Prettier does better, so we import both and achieve each of the advantages. About the conflict of the formatting part, we can import plugin:prettier/recommended to solve this, but keep in mind that this plugin should extend at the last.

# Config File
ā””ā”€ā”€ .prettierrc.js

Editorconfig

It defines a standard code formatting style guide among all the IDEs and editors used within a team of developers. Basically, all the rules in the Editorconfig should sync with Prettier, Editorconfig focus on newly created files, ESLint and Prettier focus on existing files.

# Config File
ā””ā”€ā”€ .editorconfig

Husky + Commitlint + Lint-staged

These tools are the wrapper of Git Hook. Lint-staged enforces you to format your code (run pnpm lint) before committing, but the tools will cache the file that is already formatted to improve performance. Commitlint enforces your commit message to fit a specific format, here we extend Conventional Commits (officially recommend setting).

# Type: build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test
# Commitlint Format:

<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
# Config File for Lint-staged
ā””ā”€ā”€ .lintstagedrc.js

# Config File for Commitlint
ā””ā”€ā”€ .commitlintrc.js

# Config File for Husky
ā”œā”€ā”€ .husky
|   ā”œā”€ā”€ commit-msg  # call Commitlint to check the commit message
|   ā”œā”€ā”€ pre-commit  # call Eslint to lint the coding issue
|   ā””ā”€ā”€ pre-push    # call Jest to do the unit + e2e test

Git Attributes

To synchronize the end-of-line of the git repository.

# Config File
ā””ā”€ā”€ .gitattributes

āš™ļø Other Configuration

SWC

SWC (stands for Speedy Web Compiler) is a super-fast TypeScript / JavaScript compiler written in Rust. NestJS v10 should be officially support it now, so we replace ts-loader to swc-loader for better building performance.

Pnpm

We use preinstall script forcing Pnpm as default package manager because it is a fast and disk space efficient manager compare with Npm and Yarn.

Webpack

We overwrite the default webpack.config.js so that the production build can bundle all required libraries in main.ts. For the configuration, we ignored a list of the nestjs-buildin library so that we could build it without error. If you need these libraries for your development, you can comment it in the lazy imports list.

Alias Path

Using an alias path can prevent dirty relative paths (e.g. ../../../), also it is easier to import files in the deep directory (e.g. src/assets/img/testing/...).

# Config File
ā””ā”€ā”€ tsconfig.json

API Response

Success Response

{
  "data": {
    "...": "..."
  }
}

Error Response

{
  "error": {
    "code": 400,
    "message": "..."
  }
}

We use Google JSON guide to be the response format implemented by filtering + interceptor, which is the built-in feature of NestJS, to sync with the response format. All exceptions will be caught by filtering, and all normal returns will be transformed by the interceptor.

# Related Directory
ā”œā”€ā”€ src
|   ā”œā”€ā”€ exception
|   ā”œā”€ā”€ filter
|   ā””ā”€ā”€ interceptor

Environment Variables Validation

We use Joi library for the validation, which is recommended by NestJS.

# Config File
ā”œā”€ā”€ src
|   ā””ā”€ā”€ app.config.ts

HTTP Request

Since @nestjs/axios default return Observable, it does not fit the common use case (Promise based), so we use a custom module to implement secondary encapsulation of the native Axios library, also extract .data from the response to prevent .data.data.data... chaining.

Reference:

Pino Logger

We used nestjs-pino to auto-log every request metadata and response time. We also centralized Pino config in app.config.ts for main.ts to reuse it.

Swagger

@nestjs/swagger allows you to auto-generate the API document, but here we decouple the document and the service. You can run pnpm swagger to generate the schema and put it into Swagger UI to host your API document as a static page. We have two examples in app.controller.ts to show you how to integrate the Google JSON response format. We also have a GitHub Action example to auto-update the schema and host it to the GitHub Pages. If you do not want this setup, you can just follow NestJS official guideline to host your document inside the service.

Attention: You do not need to wrap the data object to your DTO for every response, you only have to name your DTO end with 'Res', swagger.ts script will auto-wrap for you and display correctly in the Swagger UI.

Swagger UI Final Output

Docker Containerization

We also set up the Dockerfile with multi-stage builds to optimize your image size and building time. For the docker-compose config, we also included health checking.

# Config File
ā”œā”€ā”€ ci
|   ā”œā”€ā”€ docker-compose.yaml
|   ā””ā”€ā”€ Dockerfile

Clustering

We also configured the clustering feature for the service to improve performance. All you need to do is just config the environment variable CLUSTERING=true.

ā˜‘ļø Naming Convention

JS variable / function: lower camel case [e.g. twoWords]

JS global const + enum's attributes: upper case [e.g. TWO_WORDS]

JS class / interface / type / enum: pascal case [e.g. TwoWords]

Asset name (e.g. image): kebab case [e.g. two-words]

šŸ“ˆ Performance Optimization

By default, we used Fastify instead of Express to achieve twice of performance, below are the benchmarks tested by NestJS:

Express.js

Stat1%2.5%50%97.5%AvgStdevMin
Req/Sec1418314183157671599115640501.1314182
Bytes/Sec3.06 MB3.06 MB3.41 MB3.45 MB3.38 MB108 kB3.06 MB

Fastify

Stat1%2.5%50%97.5%AvgStdevMin
Req/Sec1993519935332473411132030.44103.8419931
Bytes/Sec3.03 MB3.03 MB5.05 MB5.19 MB4.87 MB624 kB3.03 MB

Reference:

License

This project is licensed under the MIT License, Copyright Ā© 2022. See LICENSE for more information.