question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

question: how to get raw request body

See original GitHub issue

I’m adding a Stripe webhook and I need to get raw request body, like:

app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {}

https://stripe.com/docs/webhooks/signatures#verify-official-libraries

How I can get it using routing-controller?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
Aitchy13commented, Aug 14, 2020

Spent all afternoon trying to figure this out too, but I have a solution:

Add the following middleware:

// RawBodyMiddleware.ts
import { Request, Response } from 'express';

const RawBodyMiddleware = (req: Request, res: Response, next: () => void) => {
  const body = []
  req.on('data', chunk => {
    body.push(chunk)
  })
  req.on('end', () => {
    const rawBody = Buffer.concat(body)
    req['rawBody'] = rawBody
    switch (req.header('content-type')) {
      case 'application/json':
        req.body = JSON.parse(rawBody.toString())
        break
      // add more body parsing if needs be
      default:
    }
    next()
  })
  req.on('error', () => {
    res.sendStatus(400)
  })
}

export default RawBodyMiddleware

In your controller, add the middleware to the endpoint that requires a raw body and access the raw body property from the request using the @Req() decorator:

import { Request, Response } from 'express';
import { Req, UseBefore } from 'routing-controllers';
import RawBodyMiddleware from '../middlewares/RawBodyMiddleware'

@Post('/myendpoint')
@UseBefore(RawBodyMiddleware)
public myEndpoint(@Req() request: Request) {
   const rawBody = request.rawBody
   const asString = rawBody.toString()

   const jsonBody = request.body
}

Hope that helps!

1reaction
JClackettcommented, Aug 24, 2021

I tried the solution above, but stripe wasn’t liking the rawBody buffer, just passing the bodyparser.raw function into the UseBefore decorator seems to work for me!

@Service()
@JsonController("/stripe")
export class StripeController {
  @HttpCode(200)
  @Post("/webhook")
  @UseBefore(raw({ type: "application/json" }))
  async stripe(@Req() request: Request, @HeaderParam("stripe-signature") signature: string) {
    let event: Stripe.Event
    if (!request.body) return false
    try {
      event = stripe.webhooks.constructEvent(request.body, signature, STRIPE_WEBHOOK_SECRET)
    } catch (err) {
      console.log("oops", err)
      return false
    }
   // do stuff with event
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I get the raw request body from the Request.Content ...
You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.
Read more >
How to get RAW request body in anonymous web service?
I want to get the full raw request body inside a POST method. Is there any way to do it since it's not...
Read more >
Reading the raw request body as a string in ASP.NET Core
In the .NET Framework version of MVC, this is simple. You first reset the position of the stream, then re-read it: Request.InputStream ...
Read more >
Raw request body - HTTPie 3.2.1 (latest) docs
There are three methods for passing raw request data: piping via stdin , --raw='data' , and @/file/path . Redirected Input. The universal method...
Read more >
Get raw request body in custom controller - Strapi Backend
const raw = ctx.request.body[Symbol.for("unparsedBody")];. Home · Categories ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found