Search code examples
javascriptnode.jsfastify

How do I access the raw body of a Fastify request?


As you may imagine, I'm familiar with Express, but this is the first time I'm using Fastify.

I'd like to access the unmodified body of a Fastify request, for signature verification of a webhook - ie, I would like to see the request as it came in, unmodified by any middleware. In Express this is often done by accessing request.rawBody.

How do I access the raw body of a Fastify request?


Solution

  • According to the docs https://docs.nestjs.com/faq/raw-body

    in main.ts

      const app = await NestFactory.create<NestFastifyApplication>(
        AppModule,
        new FastifyAdapter(),
        {
          rawBody: true,
        },
      );
    

    Then in your controller

      async handleStripeEvent(
        @Headers('stripe-signature') signature: string,
        @Req() request: RawBodyRequest<FastifyRequest>,
      ) {
        if (!signature) {
          throw new BadRequestException('Missing stripe-signature header');
        }
    
        const event = await this.webhooksService.handleStripePaymentWebhook(
          signature,
          request.rawBody,
        );
      }