Security

In this chapter you will learn some techniques that will allow you to increase the security of your applications.

Helmet

Helmet can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately. Generally, Helmet is just a collection of 12 smaller middleware functions that set security-related HTTP headers (read more). Firstly, install the required package:

  1. $ npm i --save helmet

Once the installation is completed, apply it as a global middleware.

  1. import * as helmet from 'helmet';
  2. // somewhere in your initialization file
  3. app.use(helmet());

CORS

Cross-origin resource sharing (CORS) is a mechanism that allows resources to be requested from another domain. Under the hood, Nest makes use of cors package, that provides a bunch of options that you may customize based on your requirements. In order to enable CORS, you have to call enableCors() method.

  1. const app = await NestFactory.create(ApplicationModule);
  2. app.enableCors();
  3. await app.listen(3000);

Also, you can pass a configuration object as a parameter of this function. The available properties are exhaustively described in the official cors repository. A different way is to use a Nest options object:

  1. const app = await NestFactory.create(ApplicationModule, { cors: true });
  2. await app.listen(3000);

Instead of passing a boolean value, you can use a cors configuration object as well (read more).

CSRF

Cross-site request forgery (known as CSRF or XSRF) is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts. To mitigate this kind of attacks you can use the csurf package. Firstly, install the required package:

  1. $ npm i --save csurf

warning Warning As explained on the csurf middleware page, the csurf module requires either a session middleware or cookie-parser to be initialized first. Please see that documentation for further instructions.

Once the installation is completed, apply it as a global middleware.

  1. import * as csurf from 'csurf';
  2. // somewhere in your initialization file
  3. app.use(csurf());

Rate limiting

To protect your applications from brute-force attacks, you have to implement some kind of rate-limiting. Luckily, there is a bunch of various middleware available on the NPM already. One of them is express-rate-limit.

  1. $ npm i --save express-rate-limit

Once the installation is completed, apply it as a global middleware.

  1. import * as rateLimit from 'express-rate-limit';
  2. // somewhere in your initialization file
  3. app.use(
  4. rateLimit({
  5. windowMs: 15 * 60 * 1000, // 15 minutes
  6. max: 100, // limit each IP to 100 requests per windowMs
  7. }),
  8. );

info Hint If you work with FastifyAdapter, consider using fastify-rate-limit instead.