DEV Community

Cover image for Decorators — Fastify with TypeScript (part 11/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Decorators — Fastify with TypeScript (part 11/18)

Decorators

Eleventh chapter of the "Fastify with TypeScript" series. Decorators let you add your own properties and methods to the Fastify instance, the request, and the reply, in a fully type-safe way. We've been using one since chapter 4 without naming it: fastify.config. In this chapter we write another, to solve a problem the next chapter would otherwise run into.


The problem: state trapped in a plugin

Our users live in an array declared inside the userRoutes plugin. That was the right place for it (chapter 5), but it means nothing outside that function can reach it. The next chapter adds an auth module with a login route, and login needs to look a user up by email. Two modules, one set of data: it has to live somewhere both can see.

A global variable would do it, and we've already said why we don't want one. The Fastify answer is a decorator: attach the data to the instance, and every plugin that receives the instance can use it.

An instance decorator

Create src/plugins/store.ts:

// src/plugins/store.ts
import fp from 'fastify-plugin';
import type { UserResponseType } from '../users/users.schema.ts';

interface Store {
  users: UserResponseType[];
}

declare module 'fastify' {
  interface FastifyInstance {
    store: Store;
  }
}

// Temporary in-memory storage shared by every module: PostgreSQL replaces it in chapter 13
export default fp(async function storePlugin(fastify) {
  fastify.decorate('store', { users: [] });
}, { name: 'store' });
Enter fullscreen mode Exit fullscreen mode

Three things are happening here:

  • fastify.decorate('store', ...) adds a store property to the instance.
  • The plugin is wrapped with fastify-plugin, so the decorator goes to the parent and every other plugin can see it (chapter 8).
  • The declare module 'fastify' block tells TypeScript that FastifyInstance now has a store of type Store. Decorators are added at runtime, so the compiler can't discover them on its own. This is called module augmentation, and it is what makes fastify.store.users typed and autocompleted everywhere.

Register it in src/app.ts. Add the import:

import store from './plugins/store.ts';
Enter fullscreen mode Exit fullscreen mode

and register it right after the openapi plugin, before the routes:

  app.register(store);
Enter fullscreen mode Exit fullscreen mode

Then, in src/users/users.route.ts, replace the comment and the line that declares the array:

  // Temporary in-memory storage: PostgreSQL replaces it in chapter 13
  const users: UserResponseType[] = [];
Enter fullscreen mode Exit fullscreen mode

with:

  const { users } = fastify.store;
Enter fullscreen mode Exit fullscreen mode

Nothing else in the file changes, and the API behaves exactly as before. The difference is that the users now belong to the application instance rather than to one plugin. Every buildApp() call still gets its own, empty store, so there is no global state.

See encapsulation again

Remove the fp(...) wrapper from store.ts for a moment (keep the function, drop fp( and the , { name: 'store' }) at the end) and start the server:

TypeError: Cannot destructure property 'users' of 'fastify.store' as it is undefined.
Enter fullscreen mode Exit fullscreen mode

Without fastify-plugin the decorator stays inside storePlugin, and the users plugin, a sibling, doesn't see it. TypeScript can't warn you about this: the declare module block says the property exists, and whether it really does depends on how the plugins are registered. Put the wrapper back.

Request and reply decorators

The instance is not the only thing you can decorate.

declare module 'fastify' {
  interface FastifyRequest {
    startedAt: number;
  }
  interface FastifyReply {
    sendError: (code: number, message: string) => FastifyReply;
  }
}

// Request: per-request state, declared once and filled in by a hook
fastify.decorateRequest('startedAt', 0);
fastify.addHook('onRequest', async (request) => {
  request.startedAt = performance.now();
});

// Reply: a response helper
fastify.decorateReply('sendError', function (this: FastifyReply, code: number, message: string) {
  return this.code(code).send({ error: message });
});
Enter fullscreen mode Exit fullscreen mode

Why decorateRequest('startedAt', 0) with a placeholder value? Fastify adds the property to the prototype shared by every request object, so that they all have the same shape from the start, which is one of the things that keeps it fast. The real value is assigned per request, in a hook.

For the same reason the placeholder must be a primitive or null. An object or an array would be one single instance shared by all requests, and Fastify refuses it outright:

The decorator 'tags' of type 'object' is a reference type. Use the { getter, setter } interface instead.
Enter fullscreen mode Exit fullscreen mode

Names already taken

A decorator name can be used only once. Adding it a second time fails at startup:

The decorator 'config' has already been added!
Enter fullscreen mode Exit fullscreen mode

This matters with official plugins, because several of them decorate for you: @fastify/jwt owns request.user, @fastify/postgres owns fastify.pg. Don't declare those names yourself. The plugin adds the decorator and ships its typings (for @fastify/jwt you'll augment an interface called FastifyJWT instead, as we'll see in the next chapter).

When a plugin needs a decorator that another plugin provides, say so with dependencies, as in chapter 8:

export default fp(plugin, { name: 'auth', dependencies: ['store'] });
Enter fullscreen mode Exit fullscreen mode

⬅️ Previous chapter: Error handling · ➡️ Next chapter: Authentication and authorization

This article is part of the "Fastify with TypeScript" series — chapter 11 of 18.

Top comments (0)