app.decorate()

Adds a custom property or method to the Fastify instance.

Since Fastify 5 Spec ↗

Syntax

app.decorate(name, value, dependencies?)

Parameters

NameTypeRequiredDescription
name string No The property name added to the instance.
value any No The value, function, or getter definition.

Returns

FastifyInstance — The instance, for chaining.

Throws

  • FastifyError — Thrown if the property already exists.

Examples

import Fastify from 'fastify';

const app = Fastify();

app.decorate('config', { apiKey: process.env.API_KEY });

declare module 'fastify' {
  interface FastifyInstance {
    config: { apiKey?: string };
  }
}

app.get('/key', async () => app.config.apiKey ?? 'none');

Notes

Decorators added at the top level are shared everywhere; those added inside a plugin stay encapsulated. Augment the FastifyInstance interface via declaration merging for type safety.