# Stripe webhooks on NestJS

NestJS on the Express adapter runs body-parser before your controller, so `@Body()` is already parsed. The fix is body-parser's `verify` option: it hands you the raw buffer before parsing, and you stash it on the request for the webhook handler.

## The setup

```
import { NestFactory } from '@nestjs/core';
import { json } from 'express';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(
    json({
      verify: (req: any, _res, buf) => {
        req.rawBody = buf;
      },
    }),
  );
  await app.listen(3000);
}
bootstrap();
```

```
import { Controller, Post, Req, Res, HttpCode } from '@nestjs/common';
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_API_KEY_VALUE);

@Controller('webhooks')
export class StripeWebhookController {
  @Post('stripe')
  @HttpCode(200)
  async handle(@Req() req: any, @Res() res: any) {
    const sig = req.headers['stripe-signature'];
    try {
      const event = stripe.webhooks.constructEvent(
        req.rawBody.toString('utf8'),
        sig,
        process.env.STRIPE_WEBHOOK_SIGNING_VALUE,
      );
      // switch on event.type ...
      return res.json({ received: true });
    } catch (err) {
      return res.status(400).send('bad signature');
    }
  }
}
```

## Notes

- This applies to the Express adapter (the default). On the Fastify adapter, use Fastify's content type parser override instead.
- `@Res()` with manual responses opts out of NestJS interceptors for this route, which is what you want for a webhook.
- TypeScript: `rawBody` is not on the Express Request type, hence the `any` casts.