Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Plugins and Encapsulation

Decorators in Depth

Add your own properties and helpers to Fastify with decorate, decorateRequest and decorateReply. Learn the rules, the this keyword, request-level state and pitfalls.

A decorator is how you attach your own things to Fastify's objects: a database client on the server instance, the authenticated user on the request, a reply.ok() helper on the reply. Instead of importing a global or monkey-patching prototypes, you register the addition and Fastify gives every handler access to it in a predictable way.

Fastify has three decorator functions, one per object: decorate for the server instance, decorateRequest for request and decorateReply for reply. This lesson covers each, the rules Fastify enforces, and the mistakes that cost the most debugging time.

Why decorate instead of using globals?

  • Scope. Decorators follow encapsulation: a decorator added in a plugin is visible only to that plugin and its children.
  • Testability. Tests can replace the db decorator with a fake by registering a different plugin.
  • Performance. Declaring decorators up front keeps the shape of Fastify's objects stable, which lets V8 optimize property access.
  • Discoverability. app.hasDecorator('db') tells you what exists, and duplicate names fail loudly.

app.decorate(name, value)

decorate adds a property to the Fastify instance. The value can be anything: a string, an object, a function, a class instance such as a database pool:

JavaScript
app.decorate('config', { currency: 'EUR', pageSize: 20 });
app.decorate('formatMoney', function (cents) {
  return `${(cents / 100).toFixed(2)} ${this.config.currency}`;
});

Handlers declared with function (not arrow functions) receive the instance as this, so they can use decorators as this.config or this.formatMoney(...). Arrow functions do not get a this, so there you use the plugin's instance variable (app.config). Both styles work; pick one and be consistent within a file.

Rules Fastify enforces:

  1. A decorator name can be added once per scope. A second decorate with the same name throws FST_ERR_DEC_ALREADY_PRESENT.
  2. Decorators must be added before the server starts (while plugins load), not while serving requests.
  3. If a decorator depends on another, say so with fastify-plugin dependencies, or register the providing plugin earlier.
Node.js Decorating the instance with a service

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 duplicate decorate('config', ...) is rejected with a clear code, which is how two plugins that both claim config get caught at start-up rather than silently overwriting each other.

decorateRequest and decorateReply

The instance exists once, but request and reply are created for every request. Their decorators describe a property every request object will have, usually filled in later by a hook:

JavaScript
app.decorateRequest('user', null);       // declare the shape; value set per request

app.addHook('onRequest', async (request) => {
  request.user = await lookupUser(request.headers.authorization);
});

Declare with null (or another simple value) and assign it per request. Two reasons:

  • Shape stability. Every request object gets the property in the same position, which keeps V8 fast. Adding unknown properties ad hoc (request.foo = 1 without declaring) works but makes Fastify objects change shape and slows hot paths.
  • No shared state between users. This is the dangerous one. If you declare decorateRequest('user', {}) with an object, every request would share that same object, and one user's data could appear in another user's request. Fastify 5 refuses reference types (objects and arrays) as initial values for request and reply decorators and throws FST_ERR_DEC_REFERENCE_TYPE. Use null and assign in a hook, or use the getter form below.

The runnable stand-in on this site does not enforce the reference-type rule, but the real framework does. Always initialize request and reply decorators with null, a number, a string or a boolean, then assign real objects in an onRequest or preHandler hook.

For computed values you can use the getter/setter form, which runs per access instead of sharing a value:

JavaScript
app.decorateRequest('isAdmin', {
  getter() { return this.user?.role === 'admin'; },
});

Reply helpers

decorateReply is perfect for response shortcuts that every route repeats:

JavaScript
app.decorateReply('ok', function (data) {
  return this.code(200).send({ ok: true, data });
});
app.decorateReply('fail', function (status, message) {
  return this.code(status).send({ ok: false, error: message });
});

Always write these as regular functions so this is the reply.

Node.js Request state and reply helpers

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.

Each request got its own request.user, and both reply helpers reduced repeated code(...).send({...}) calls to one readable line. Handlers now read like a description of intent: "fail with 403", "reply ok".

Checking and organizing decorators

Function Purpose
app.hasDecorator('name') Is the instance decorator present in this scope?
app.hasRequestDecorator('name') Is a request decorator present?
app.hasReplyDecorator('name') Is a reply decorator present?
app.getDecorator('name') Fetch an instance decorator (throws if missing)

Practical tips:

  • Group related helpers in one object (app.decorate('services', { users, orders })) rather than dozens of top-level names, to avoid collisions.
  • Prefix names from reusable plugins (app.decorate('myAuthUser', ...)) so they cannot collide with another plugin's.
  • Document decorators in TypeScript by augmenting Fastify's interfaces:
TypeScript
declare module 'fastify' {
  interface FastifyInstance { config: { currency: string; pageSize: number } }
  interface FastifyRequest { user: { name: string; role: string } | null }
}

(Type augmentation is TypeScript-only and read-only here.)

Common mistakes

  • Declaring an object on decorateRequest. It would be shared by all requests; use null and assign per request.
  • Arrow functions that use this. this is not the instance or reply there. Use function or the closure variable.
  • Decorating from inside a handler or after ready. Decorators are start-up configuration.
  • Duplicate names across plugins. The second registration throws; prefix names or share through a single plugin.
  • Forgetting encapsulation. A decorator added in one plugin is invisible to siblings; see the next lesson for sharing.
  • Using decorators as a dumping ground. If it is not used in several places, a plain imported module is simpler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method adds a property to every request object?

    decorateRequest declares a property on request; decorate is for the server instance and decorateReply for reply.
  2. 2. Why should decorateRequest('user', {}) be avoided?

    An initial reference value is shared. Declare with null and assign a fresh object per request in a hook.
  3. 3. What happens if two plugins in the same scope call app.decorate('db', ...)?

    A name can be decorated once per scope, which catches accidental collisions at start-up.
  4. 4. Why write a reply helper as a regular function instead of an arrow function?

    Fastify calls the helper as a method of the reply, so this is the reply only for regular functions.

Summary

  • decorate extends the instance, decorateRequest the request and decorateReply the reply; all respect encapsulation.
  • A name can be decorated once per scope and only while the app is starting.
  • Declare request and reply decorators with null (never an object) and fill them per request in a hook, or use the getter form.
  • Reply helpers like reply.ok() remove repetition; write them as regular functions so this is the reply.
  • Prefix names in shared plugins and add TypeScript declarations for editor help.

Next: fastify-plugin and Sharing