Peter Karabinovich
Peter Karabinovich

Reputation: 633

Use default JSON parser in Fastify addContentTypeParser

Good day,

Please help with reaching fastify default parser.

What I need is assign JSON-body parser on every request regardless content-type header

Currently, I have done it with that ugly workaround:

const {kContentTypeParser} = require("fastify/lib/symbols")
const asJson = fastify[kContentTypeParser].customParsers["application/json"]
fastify.addContentTypeParser("*", asJson);

Thank you in advance

Upvotes: 1

Views: 3230

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

In fastify <=v2.11 the default content type parser is not exposed.

Since it applies many checks (like prototype poisoning, content length, etc..) you should be careful before overwrite.

Your target can be archived adding an hook:

fastify.addHook('onRequest', (request, reply, done) => {
  const type = request.getHeader('content-type')
  if(!type || type.indexOf('json') < 0){
    // force json body parse
    request.headers['content-type'] = 'application/json'
  }
  done()
})

Upvotes: 1

Related Questions