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 register it will be available only in that scope and its children.

    Fastify adds automatically the parsed request payload to the object, you can reach it with request.body.

    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 (req, done) {
    3. })
    4. }

    Body Parser

    As you can see, now the function signature is (req, body, done) instead of (req, done).

    See for an example.

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

    Catch All

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

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

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

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

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

    Here is a complete example that logs incoming objects: