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

Viewed 11916

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?

2 Answers

Note: Fastify requests can only have req.body - they can't have, for example, req.body and req.rawBody like other web servers (for example, Express). This is because addContentTypeParser() only returns a modified body, it can't add anything else to the request.

Instead, in a content type parser we only add to one route, we make:

  • req.body.parsed (the object, same content that would normally be in req.body)
  • req.body.raw (the string)

See GitHub and the addContentTypeParser() docs for more.

  server.addContentTypeParser(
    "application/json",
    { parseAs: "string" },
    function (req, body, done) {
      try {
        var newBody = {
          raw: body,
          parsed: JSON.parse(body),
        };
        done(null, newBody);
      } catch (error) {
        error.statusCode = 400;
        done(error, undefined);
      }
    }
  );

There's an issue on GitHub for rawBody support

And there's a module too: "raw-body". To use this module in Fastify:

const rawBody = require('raw-body')

fastify.addContentTypeParser('*', (req, done) => {
    rawBody(req, {
        length: req.headers['content-length'],
        limit: '1mb',
        encoding: 'utf8', // Remove if you want a buffer
    }, (err, body) => {
        if (err) return done(err)
        done(null, parse(body))
    })
})

I hope that I helped you, I'm new on fastify too

Related