Decorators

If you need to add functionality to the Fastify instance, the decorate API is what you need.

The API allows you to add new properties to the Fastify instance. A value is not restricted to a function and could also be an object or a string, for example.

Usage

decorate Just call the decorate API and pass the name of the new property and its value.

  1. fastify.decorate('utility', () => {
  2. // something very useful
  3. })

As said above, you can also decorate the instance with non-function values:

  1. fastify.decorate('conf', {
  2. db: 'some.db',
  3. port: 3000
  4. })

Once you decorate the instance, you can access the value by using the name you passed as a parameter:

  1. fastify.utility()
  2. console.log(fastify.conf.db)

decorateReply As the name suggests, this API is needed if you want to add new methods to the Reply core object. Just call the decorateReply API and pass the name of the new property and its value:

  1. fastify.decorateReply('utility', function () {
  2. // something very useful
  3. })

Note: using an arrow function will break the binding of this to the Fastify reply instance.

decorateRequest As above, this API is needed if you want to add new methods to the Request core object. Just call the decorateRequest API and pass the name of the new property and its value:

  1. fastify.decorateRequest('utility', function () {
  2. // something very useful
  3. })

Note: using an arrow function will break the binding of this to the Fastify request instance.

Decorators and encapsulation

If you define a decorator (using decorate, decorateRequest or decorateReply) with the same name more than once in the same encapsulated plugin, fastify will throw an exception.

As an example, the following will throw:

  1. const server = require('fastify')()
  2. server.decorateReply('view', function (template, args) {
  3. // Amazing view rendering engine.
  4. })
  5. server.get('/', (req, reply) => {
  6. reply.view('/index.html', { hello: 'world' })
  7. })
  8. // Somewhere else in our codebase, we define another
  9. // view decorator. This throws.
  10. server.decorateReply('view', function (template, args) {
  11. // another rendering engine
  12. })
  13. server.listen(3000)

But this will not:

  1. const server = require('fastify')()
  2. server.decorateReply('view', function (template, args) {
  3. // Amazing view rendering engine.
  4. })
  5. server.register(async function (server, opts) {
  6. // We add a view decorator to the current encapsulated
  7. // plugin. This will not throw as outside of this encapsulated
  8. // plugin view is the old one, while inside it is the new one.
  9. server.decorateReply('view', function (template, args) {
  10. // another rendering engine
  11. })
  12. server.get('/', (req, reply) => {
  13. reply.view('/index.page', { hello: 'world' })
  14. })
  15. }, { prefix: '/bar' })
  16. server.listen(3000)

Getters and Setters

Decorators accept special "getter/setter" objects. These objects have functions named getter and setter (though, the setter function is optional). This allows defining properties via decorators. For example:

  1. fastify.decorate('foo', {
  2. getter () {
  3. return 'a getter'
  4. }
  5. })

Will define the foo property on the Fastify instance:

  1. console.log(fastify.foo) // 'a getter'

Usage Notes

decorateReply and decorateRequest are used to modify the Reply and Request constructors respectively by adding methods or properties. To update these properties you should directly access the desired property of the Reply or Request object.

As an example let's add a user property to the Request object:

  1. // Decorate request with a 'user' property
  2. fastify.decorateRequest('user', '')
  3. // Update our property
  4. fastify.addHook('preHandler', (req, reply, next) => {
  5. req.user = 'Bob Dylan'
  6. next()
  7. })
  8. // And finally access it
  9. fastify.get('/', (req, reply) => {
  10. reply.send(`Hello ${req.user}!`)
  11. })

Note: The usage of decorateReply and decorateRequest is optional in this case but will allow Fastify to optimize for performance.

Sync and Async

decorate is a synchronous API. If you need to add a decorator that has an asynchronous bootstrap, Fastify could boot up before your decorator is ready. To avoid this issue, you must use the register API in combination with fastify-plugin. To learn more, check out the Plugins documentation as well.

Dependencies

If your decorator depends on another decorator, you can easily declare the other decorator as a dependency. You just need to add an array of strings (representing the names of the decorators on which yours depends) as the third parameter:

  1. fastify.decorate('utility', fn, ['greet', 'log'])

If a dependency is not satisfied, decorate will throw an exception, but don't worry: the dependency check is executed before the server boots up, so it won't ever happen at runtime.

hasDecorator

You can check for the presence of a decorator with the hasDecorator API:

  1. fastify.hasDecorator('utility')

hasRequestDecorator

You can check for the presence of a Request decorator with the hasRequestDecorator API:

  1. fastify.hasRequestDecorator('utility')

hasReplyDecorator

You can check for the presence of a Reply decorator with the hasReplyDecorator API:

  1. fastify.hasReplyDecorator('utility')