Search code examples
feathersjs

Get raw request body in feathers


I try to implement a WooCommerce webhook functionality for feathers. To authenticate the request I need to verify the signature of the raw request body like so

const isSignatureValid = (
      secret: string,
      body: any,
      signature?: string
    ): boolean => {
      const signatureComputed = crypto
        .createHmac("SHA256", secret)
        .update(new Buffer(JSON.stringify(body), "utf8"))
        .digest("base64");

      return signatureComputed === signature ? true : false;
    };

Currently my signature never verifies. My guess is that this is due to the fact that req.body is not the acutual raw body of the request but some already parsed version with some featherjs goodness added.

Question is: How do I obtain the raw request body in a standard feathers app (created with feathers cli)?


Solution

  • Not sure if this is the most idiomatic way to do this, but I came up with the following:

    In of express.json() in the main app.ts file it is possible to add the raw, unparsed body to the req object. This is handy, as for some webhooks (woocommerce, stripe), you only need the raw body to verifiy the signature, but otherwise work with the parsed JSON.

    export interface IRequestRawBody extends http.IncomingMessage {
      rawBody: Buffer;
    }
    
    app.use(
      express.json({
        verify: (req: IRequestRawBody, res, buf) => {
          const rawEndpoints: string[] = ["/wc-webhook"];
    
          if (req.url && rawEndpoints.includes(req.url)) {
            req.rawBody = buf;
          }
        }
      })
    );