Content-Type Parser

Natively, Fastify only supports 'application/json' and 'text/plain' content types. The default charset is utf-8. If you need to support different content types, you can use the addContentTypeParser API. The default JSON and/or plain text parser can be changed.

Note: If you decide to specify your own content type with the Content-Type header, UTF-8 will not be the default. Be sure to include UTF-8 like this text/html; charset=utf-8.

As with the other APIs, addContentTypeParser is encapsulated in the scope in which it is declared. This means that if you declare it in the root scope it will be available everywhere, while if you declare it inside a plugin it will be available only in that scope and its children.

Fastify automatically adds the parsed request payload to the Fastify request object which you can access with request.body.

Usage

  1. fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
  2. jsoffParser(payload, function (err, body) {
  3. done(err, body)
  4. })
  5. })
  6. // Handle multiple content types with the same function
  7. fastify.addContentTypeParser(['text/xml', 'application/xml'], function (request, payload, done) {
  8. xmlParser(payload, function (err, body) {
  9. done(err, body)
  10. })
  11. })
  12. // Async is also supported in Node versions >= 8.0.0
  13. fastify.addContentTypeParser('application/jsoff', async function (request, payload) {
  14. var res = await jsoffParserAsync(payload)
  15. return res
  16. })
  17. // Handle all content types that matches RegExp
  18. fastify.addContentTypeParser(/^image\/.*/, function (request, payload, done) {
  19. imageParser(payload, function (err, body) {
  20. done(err, body)
  21. })
  22. })
  23. // Can use default JSON/Text parser for different content Types
  24. fastify.addContentTypeParser('text/json', { parseAs: 'string' }, fastify.getDefaultJsonParser('ignore', 'ignore'))

Fastify first tries to match a content-type parser with a string value before trying to find a matching RegExp. If you provide overlapping content types, Fastify tries to find a matching content type by starting with the last one passed and ending with the first one. So if you want to specify a general content type more precisely, first specify the general content type and then the more specific one, like in the example below.

  1. // Here only the second content type parser is called because its value also matches the first one
  2. fastify.addContentTypeParser('application/vnd.custom+xml', (request, body, done) => {} )
  3. fastify.addContentTypeParser('application/vnd.custom', (request, body, done) => {} )
  4. // Here the desired behavior is achieved because fastify first tries to match the `application/vnd.custom+xml` content type parser
  5. fastify.addContentTypeParser('application/vnd.custom', (request, body, done) => {} )
  6. fastify.addContentTypeParser('application/vnd.custom+xml', (request, body, done) => {} )

You can also use the hasContentTypeParser API to find if a specific content type parser already exists.

  1. if (!fastify.hasContentTypeParser('application/jsoff')){
  2. fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
  3. jsoffParser(payload, function (err, body) {
  4. done(err, body)
  5. })
  6. })
  7. }

Notice: The old syntaxes function(req, done) and async function(req) for the parser are still supported but they are deprecated.

Body Parser

You can parse the body of a request in two ways. The first one is shown above: you add a custom content type parser and handle the request stream. In the second one, you should pass a parseAs option to the addContentTypeParser API, where you declare how you want to get the body. It could be of type 'string' or 'buffer'. If you use the parseAs option, Fastify will internally handle the stream and perform some checks, such as the maximum size of the body and the content length. If the limit is exceeded the custom parser will not be invoked.

  1. fastify.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) {
  2. try {
  3. var json = JSON.parse(body)
  4. done(null, json)
  5. } catch (err) {
  6. err.statusCode = 400
  7. done(err, undefined)
  8. }
  9. })

See example/parser.js for an example.

Custom Parser Options
  • parseAs (string): Either 'string' or 'buffer' to designate how the incoming data should be collected. Default: 'buffer'.
  • bodyLimit (number): The maximum payload size, in bytes, that the custom parser will accept. Defaults to the global body limit passed to the Fastify factory function.

Catch-All

There are some cases where you need to catch all requests regardless of their content type. With Fastify, you can just use the '*' content type.

  1. fastify.addContentTypeParser('*', function (request, payload, done) {
  2. var data = ''
  3. payload.on('data', chunk => { data += chunk })
  4. payload.on('end', () => {
  5. done(null, data)
  6. })
  7. })

Using this, all requests that do not have a corresponding content type parser will be handled by the specified function.

This is also useful for piping the request stream. You can define a content parser like:

  1. fastify.addContentTypeParser('*', function (request, payload, done) {
  2. done()
  3. })

and then access the core HTTP request directly for piping it where you want:

  1. app.post('/hello', (request, reply) => {
  2. reply.send(request.raw)
  3. })

Here is a complete example that logs incoming json line objects:

  1. const split2 = require('split2')
  2. const pump = require('pump')
  3. fastify.addContentTypeParser('*', (request, payload, done) => {
  4. done(null, pump(payload, split2(JSON.parse)))
  5. })
  6. fastify.route({
  7. method: 'POST',
  8. url: '/api/log/jsons',
  9. handler: (req, res) => {
  10. req.body.on('data', d => console.log(d)) // log every incoming object
  11. }
  12. })

For piping file uploads you may want to check out this plugin.