V3 Migration Guide

This guide is intended to help with migration from Fastify v2 to v3.

Before beginning please ensure that any deprecation warnings from v2 are fixed. All v2 deprecations have been removed and they will no longer work after upgrading. (#1750)

Breaking changes

Changed middleware support (#2014)

From Fastify v3, middleware support does not come out-of-the-box with the framework itself.

If you use Express middleware in your application, please install and register the fastify-express or middie plugin before doing so.

v2:

  1. // Using the Express `cors` middleware in Fastify v2.
  2. fastify.use(require('cors')());

v3:

  1. // Using the Express `cors` middleware in Fastify v3.
  2. await fastify.register(require('fastify-express'));
  3. fastify.use(require('cors')());

Changed logging serialization (#2017)

The logging Serializers have been updated to now Fastify Request and Reply objects instead of native ones.

Any custom serializers must be updated if they rely upon request or reply properties that are present on the native objects but not the Fastify objects.

v2:

  1. const fastify = require('fastify')({
  2. logger: {
  3. serializers: {
  4. res(res) {
  5. return {
  6. statusCode: res.statusCode,
  7. customProp: res.customProp
  8. };
  9. }
  10. }
  11. }
  12. });

v3:

  1. const fastify = require('fastify')({
  2. logger: {
  3. serializers: {
  4. res(reply) {
  5. return {
  6. statusCode: reply.statusCode, // No change required
  7. customProp: reply.raw.customProp // Log custom property from res object
  8. };
  9. }
  10. }
  11. }
  12. });

Changed schema substitution (#2023)

The non-standard replace-way shared schema support has been removed. This feature has been replaced with JSON Schema specification compliant $ref based substitution. To help understand this change read Validation and Serialization in Fastify v3.

v2:

  1. const schema = {
  2. body: 'schemaId#'
  3. };
  4. fastify.route({ method, url, schema, handler });

v3:

  1. const schema = {
  2. body: {
  3. $ref: 'schemaId#'
  4. }
  5. };
  6. fastify.route({ method, url, schema, handler });

Changed schema validation options (#2023)

The setSchemaCompiler and setSchemaResolver options have been replaced with the setValidatorCompiler to enable future tooling improvements. To help understand this change read Validation and Serialization in Fastify v3.

v2:

  1. const fastify = Fastify();
  2. const ajv = new AJV();
  3. ajv.addSchema(schemaA);
  4. ajv.addSchema(schemaB);
  5. fastify.setSchemaCompiler(schema => ajv.compile(schema));
  6. fastify.setSchemaResolver(ref => ajv.getSchema(ref).schema);

v3:

  1. const fastify = Fastify();
  2. const ajv = new AJV();
  3. ajv.addSchema(schemaA);
  4. ajv.addSchema(schemaB);
  5. fastify.setValidatorCompiler(({ schema, method, url, httpPart }) =>
  6. ajv.compile(schema)
  7. );

Changed preParsing hook behavior (#2286)

From Fastify v3, the behavior of the preParsing hook will change slightly in order to support request payload manipulation.

The hook now takes an additional argument, payload, and therefore the new hook signature is fn(request, reply, payload, done) or async fn(request, reply, payload).

The hook can optionally return a new stream via done(null, stream) or returning the stream in case of async functions.

If the hook returns a new stream, it will be used instead of the original one in subsequent hooks. A sample use case for this is handling compressed requests.

The new stream should add the receivedEncodedLength property to the stream that should reflect the actual data size received from the client. For instance, in a compressed request it should be the size of the compressed payload. This property can (and should) be dynamically updated during data events.

The old syntax of Fastify v2 without payload is supported but it is deprecated.

Changed hooks behavior (#2004)

From Fastify v3, the behavior of onRoute and onRegister hooks will change slightly in order to support hook encapsulation.

  • onRoute - The hook will be called asynchronously. The hook is now inherited when registering a new plugin within the same encapsulation scope. Thus, this hook should be registered before registering any plugins.
  • onRegister - Same as the onRoute hook. The only difference is that now the very first call will no longer be the framework itself, but the first registered plugin.

Changed Content Type Parser syntax (#2286)

In Fastify v3 the content type parsers now have a single signature for parsers.

The new signatures are fn(request, payload, done) or async fn(request, payload). Note that request is now a Fastify request, not an IncomingMessage. The payload is by default a stream. If the parseAs option is used in addContentTypeParser, then payload reflects the option value (string or buffer).

The old signatures fn(req, [done]) or fn(req, payload, [done]) (where req is IncomingMessage) are still supported but are deprecated.

Changed TypeScript support

The type system was changed in Fastify version 3. The new type system introduces generic constraining and defaulting, plus a new way to define schema types such as a request body, querystring, and more!

v2:

  1. interface PingQuerystring {
  2. foo?: number;
  3. }
  4. interface PingParams {
  5. bar?: string;
  6. }
  7. interface PingHeaders {
  8. a?: string;
  9. }
  10. interface PingBody {
  11. baz?: string;
  12. }
  13. server.get<PingQuerystring, PingParams, PingHeaders, PingBody>(
  14. '/ping/:bar',
  15. opts,
  16. (request, reply) => {
  17. console.log(request.query); // This is of type `PingQuerystring`
  18. console.log(request.params); // This is of type `PingParams`
  19. console.log(request.headers); // This is of type `PingHeaders`
  20. console.log(request.body); // This is of type `PingBody`
  21. }
  22. );

v3:

  1. server.get<{
  2. Querystring: PingQuerystring;
  3. Params: PingParams;
  4. Headers: PingHeaders;
  5. Body: PingBody;
  6. }>('/ping/:bar', opts, async (request, reply) => {
  7. console.log(request.query); // This is of type `PingQuerystring`
  8. console.log(request.params); // This is of type `PingParams`
  9. console.log(request.headers); // This is of type `PingHeaders`
  10. console.log(request.body); // This is of type `PingBody`
  11. });

Manage uncaught exception (#2073)

In sync route handlers, if an error was thrown the server crashed by design without calling the configured .setErrorHandler(). This has changed and now all unexpected errors in sync and async routes are managed.

v2:

  1. fastify.setErrorHandler((error, request, reply) => {
  2. // this is NOT called
  3. reply.send(error)
  4. })
  5. fastify.get('/', (request, reply) => {
  6. const maybeAnArray = request.body.something ? [] : 'I am a string'
  7. maybeAnArray.substr() // Thrown: [].substr is not a function and crash the server
  8. })

v3:

  1. fastify.setErrorHandler((error, request, reply) => {
  2. // this IS called
  3. reply.send(error)
  4. })
  5. fastify.get('/', (request, reply) => {
  6. const maybeAnArray = request.body.something ? [] : 'I am a string'
  7. maybeAnArray.substr() // Thrown: [].substr is not a function, but it is handled
  8. })

Further additions and improvements