NestJS Logo

Security

In this chapter we cover various techniques that help 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 14 smaller middleware functions that set security-related HTTP headers (read more).

Start by installing the required package. If you are using Express (default in Nest):


$ npm i --save helmet

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


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

If you are using the FastifyAdapter, you'll need fastify-helmet instead:


$ npm i --save fastify-helmet

fastify-helmet should not be used as a middleware, but as a Fastify plugin, i.e., by using app.register():


import * as helmet from 'fastify-helmet';
// somewhere in your initialization file
app.register(helmet);
// or the following, but note that it's not type safe
// app.getHttpAdapter().register(helmet);
Hint Note that applying helmet as global or registering it must come before other calls to app.use() or setup functions that may call app.use()). This is due to the way the underlying platform (i.e., Express or Fastify) works, where the order that middleware/routes are defined matters. If you use middleware like helmet or cors after you define a route, then that middleware will not apply to that route, it will only apply to middleware defined after the route.

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 the Express cors package. This package provides various options that you can customize based on your requirements. To enable CORS, call the enableCors() method on the Nest application object.


const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);

The enableCors() method takes an optional configuration object argument. The available properties of this object are described in the official CORS documentation.

Alternatively, enable CORS via the create() method's options object. Set the cors property to true to enable CORS with default settings. Alternatively, pass a CORS configuration object as the cors property value to customize its behavior.


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

CSRF#

Cross-site request forgery (also 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 attack you can use the csurf package.

Start by installing the required package:


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

Once the installation is complete, apply the csurf middleware as global middleware.


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

Rate limiting#

A common technique to protect applications from brute-force attacks is rate-limiting. Many Express packages exist to provide a rate-limiting feature. A popular one is express-rate-limit.

Start by installing the required package:


$ npm i --save express-rate-limit

Once the installation is complete, apply the rate-limiter as global middleware.


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

When there is a load balancer or reverse proxy between the server and the internet, Express may need to be configured to trust the headers set by the proxy in order to get the correct IP for the end user. To do so, first use the NestExpressApplication platform interface when creating your app instance, then enable the trust proxy setting:


const app = await NestFactory.create<NestExpressApplication>(AppModule);
// see https://expressjs.com/en/guide/behind-proxies.html
app.set('trust proxy', 1);
Hint If you use the FastifyAdapter, consider using fastify-rate-limit instead.

Support us

Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.

Principal Sponsors

Sanofi LogoValor Logo

Sponsors / Partners

Become a sponsor