Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Serialization and Performance

Content-Type Parsers, Streams and Custom Replies

Teach Fastify new body formats with addContentTypeParser, understand body limits and 415 errors, and send text, buffers, streams and redirects with the reply API.

By default Fastify understands two kinds of request bodies: application/json and text/plain. Anything else gets a 415 Unsupported Media Type before your handler runs. That strictness is a feature: your code never has to guess what bytes it received. When you do need another format (CSV uploads, XML webhooks, a custom binary protocol), you register a content-type parser that turns the raw payload into a JavaScript value.

The other direction matters as well. Responses are not always JSON objects: you send text, files, streams and redirects. This lesson covers both sides of the HTTP exchange.

Fastify is not installed on this site, so the first example uses the stand-in framework from The Fastify Request Lifecycle. Its addContentTypeParser(type, (request, body) => value) is simplified. The second example uses the real Node.js http module, which is exactly what Fastify builds on.

Writing a parser

In real Fastify you register a parser with a content type (or a list, or a regular expression) and decide how the body is read:

JavaScript
// real Fastify
app.addContentTypeParser('text/csv', { parseAs: 'string' }, (request, body, done) => {
  try {
    done(null, body.trim().split('\n').map((line) => line.split(',')));
  } catch (err) {
    err.statusCode = 400;
    done(err, undefined);
  }
});

parseAs can be 'string' or 'buffer'; Fastify then collects the whole body (respecting the size limit) and hands it to you. Without parseAs, your function receives the raw stream and you decide how to consume it, which is the way to handle large uploads without holding them in memory. There is also an async form, async (request, payload) => value, so the parser can be written with await.

The result is stored in request.body, and validation still runs afterwards. That means a CSV body can be checked by a body schema just like JSON: your parser produces the rows, the schema checks that they have the right shape.

Node.js A CSV parser and the 415 error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The XML request is refused with 415 before any handler or validation, because Fastify has no parser for application/xml. In real Fastify the error also carries a stable code (FST_ERR_CTP_INVALID_MEDIA_TYPE), which is handy in tests.

Body size limits

Reading a body costs memory, so Fastify caps it. The default bodyLimit is 1 MiB (1,048,576 bytes); bigger requests are rejected with 413 Payload Too Large. Set a different cap globally with Fastify({ bodyLimit: 5 * 1024 * 1024 }) or per route with the bodyLimit route option. The rule of thumb is to keep the global limit small and raise it only on the routes that need it, such as an upload endpoint. A generous global limit is an easy way for one client to tie up memory.

Other body formats usually come from official plugins rather than hand-written parsers: @fastify/formbody for application/x-www-form-urlencoded, and @fastify/multipart for file uploads, which streams files instead of buffering them.

Replies are not always JSON

What the handler returns decides the response type:

You send Content-Type set by Fastify
An object or array application/json; charset=utf-8
A string text/plain; charset=utf-8
A Buffer application/octet-stream
A Stream application/octet-stream (set your own)
null or nothing Body empty

Override the default with reply.type(), and add anything else with reply.header():

JavaScript
// real Fastify
app.get('/hello.html', async (request, reply) => {
  return reply.type('text/html; charset=utf-8').send('<h1>Hello</h1>');
});

app.get('/old-docs', async (request, reply) => reply.redirect('/docs', 301));

app.get('/download', async (request, reply) => {
  reply.header('content-disposition', 'attachment; filename="report.csv"');
  return reply.type('text/csv').send('id,total\n1,10\n2,25\n');
});

For redirects, Fastify 5 uses reply.redirect(url, code) and defaults to 302 when the code is omitted.

Streams: sending without holding everything in memory

A file of 2 GB must not be read into a variable. Send a stream and Fastify pipes it to the socket, handling back-pressure (it pauses the source when the client is slow) and errors for you:

JavaScript
// real Fastify
import { createReadStream } from 'node:fs';

app.get('/video', async (request, reply) => {
  return reply.type('video/mp4').send(createReadStream('./media/intro.mp4'));
});

Underneath, this is plain Node. The next example does the same thing with the built-in server so you can see what a streamed response looks like on the wire: a loop produces chunks over time, the server writes them as they are ready, and the client reads them one by one.

Node.js Streaming a response chunk by chunk (plain Node)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server never builds the whole text; it forwards each piece as it appears, and the response uses chunked transfer encoding because the total length is unknown.

Practical advice

  • Add parsers only for formats you really accept; each one is attack surface.
  • Raise bodyLimit per route, not globally.
  • When you must keep the raw body (for example to verify a webhook signature), use a parser with parseAs: 'buffer', store the buffer on the request, then parse it yourself.
  • Always set a precise content-type when you send non-JSON data. Browsers act on it.
  • For files and large payloads, prefer streams.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client posts application/xml and no parser is registered for it. What happens?

    Only registered content types are parsed. Others are rejected with 415 before validation and the handler.
  2. 2. What is the default body size limit?

    bodyLimit defaults to 1 MiB (1,048,576 bytes). Larger bodies get a 413.
  3. 3. Which Content-Type does Fastify use when you send a string?

    Strings are sent as plain text. Use reply.type('text/html') or similar to change that.
  4. 4. Why send a stream for a large file instead of reading it into memory?

    Streaming forwards chunks as they are read, so memory use is constant, and slow clients pause the source instead of piling up data.

Summary

  • Fastify parses application/json and text/plain; everything else needs addContentTypeParser or a plugin, otherwise it is a 415.
  • Validation runs after parsing, so custom formats can still be schema-checked.
  • Keep bodyLimit low globally (1 MiB default) and raise it on specific routes.
  • The reply type follows the payload: objects are JSON, strings text, buffers and streams octet-stream unless you call reply.type.
  • Use streams for big files, and reply.redirect(url, code) for redirects.

Next: Performance Tuning Fastify Applications