Access raw body of Stripe webhook in Nest.js

后端 未结 4 1727
抹茶落季
抹茶落季 2021-02-03 11:36

I need to access the raw body of the webhook request from Stripe in my Nest.js application.

Following this example, I added the below to the module which has a controlle

4条回答
  •  渐次进展
    2021-02-03 12:18

    For anyone looking for a more elegant solution, turn off the bodyParser in main.ts. Create two middleware functions, one for rawbody and the other for json-parsed-body.

    json-body.middleware.ts

    import { Request, Response } from 'express';
    import * as bodyParser from 'body-parser';
    import { Injectable, NestMiddleware } from '@nestjs/common';
    
    @Injectable()
    export class JsonBodyMiddleware implements NestMiddleware {
        use(req: Request, res: Response, next: () => any) {
            bodyParser.json()(req, res, next);
        }
    }
    

    raw-body.middleware.ts

    import { Injectable, NestMiddleware } from '@nestjs/common';
    import { Request, Response } from 'express';
    import * as bodyParser from 'body-parser';
    
    @Injectable()
    export class RawBodyMiddleware implements NestMiddleware {
        use(req: Request, res: Response, next: () => any) {
            bodyParser.raw({type: '*/*'})(req, res, next);
        }
    }
    

    And apply the middleware functions to appropriate routes in app.module.ts.

    app.module.ts

    [...]
    
    export class AppModule implements NestModule {
        public configure(consumer: MiddlewareConsumer): void {
            consumer
                .apply(RawBodyMiddleware)
                .forRoutes({
                    path: '/stripe-webhooks',
                    method: RequestMethod.POST,
                })
                .apply(JsonBodyMiddleware)
                .forRoutes('*');
        }
    }
    
    [...]
    

    BTW req.rawbody has been removed from express long ago.

    https://github.com/expressjs/express/issues/897

提交回复
热议问题