How to configure Helmet in a Nestjs project using Fastify?

4.8k Views Asked by At

I'm using Nestjs (7.x) and Fastify (with @nestjs/platform-fastify). I'm trying to install Helmet in my project (fastify-helmet), but I'm not able to figure how to integrate/configure it with Nestjs. What's the proper way to have it onboard?

Here is my Nestjs bootstrap:

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { MainModule } from './main.module';
import * as helmet from 'fastify-helmet';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(MainModule);
  await app.listen(3000, 0.0.0.0);
}
bootstrap();
2

There are 2 best solutions below

1
On
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { fastifyHelmet } from 'fastify-helmet';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.register(fastifyHelmet)
  await app.listen(3000);
}
bootstrap();

try this instead. import fastifyHelmet from the package, use that to register.

2
On

You've got two options when it comes to registering middleware for fastify. The first is to get the instance of the HttpAdapter and use the register method from there. This can be done like so:

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import * as helmet from 'fastify-helmet';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app
    .getHttpAdapter()
    .getInstance()
    .register(helmet);
  await app.listen(3000);
}
bootstrap();

The other option is to pass the type to the NestFactory.create method and then use app.register. This can bee seen here

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import * as helmet from 'fastify-helmet';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.register(helmet);
  await app.listen(3000);
}
bootstrap();

Both ways are valid, though only the second option is type safe.