This API is synchronous. Attempting to define a decoration asynchronously could result in the Fastify instance booting before the decoration completes its initialization. To avoid this issue, and register an asynchronous decoration, the register API, in combination with fastify-plugin, must be used instead. To learn more, see the documentation.

    Decorating core objects with this API allows the underlying JavaScript engine to optimize the handling of server, request, and reply objects. This is accomplished by defining the shape of all such object instances before they are instantiated and used. As an example, the following is not recommended because it will change the shape of objects during their lifecycle:

    Since the above example mutates the request object after it has already been instantiated, the JavaScript engine must deoptimize access to the request object. By using the decoration API this deoptimization is avoided:

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

    Note that it is important to keep the initial shape of a decorated field as close as possible to the value intended to be set dynamically in the future. Initialize a decorator as a '' if the intended value is a string, and as null if it will be an object or a function.

    Remember this example works only with value types as reference types will be shared amongst all requests. See decorateRequest.

    See for more information on this topic.

    decorate(name, value, [dependencies])

    This method is used to customize the Fastify instance.

    For example, to attach a new method to the server instance:

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

    As mentioned above, non-function values can be attached:

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

    To access decorated properties, use the name provided to the decoration API:

    1. fastify.utility()
    2. console.log(fastify.conf.db)
    1. fastify.get('/', async function (request, reply) {
    2. reply({hello: await this.db.query('world')})
    3. })

    The dependencies parameter is an optional list of decorators that the decorator being defined relies upon. This list is simply a list of string names of other decorators. In the following example, the “utility” decorator depends upon “greet” and “log” decorators:

    Note: using an arrow function will break the binding of this to the FastifyInstance.

    If a dependency is not satisfied, the decorate method will throw an exception. The dependency check is performed before the server instance is booted. Thus, it cannot occur during runtime.

    decorateReply(name, value, [dependencies])

    As the name suggests, this API is used to add new methods/properties to the core object:

    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.

    Note: using decorateReply will emit a warning if used with a reference type:

    1. // Don't do this
    2. fastify.decorateReply('foo', { bar: 'fizz'})

    In this example, the reference of the object is shared with all the requests: any mutation will impact all requests, potentially creating security vulnerabilities or memory leaks. To achieve proper encapsulation across requests configure a new value for each incoming request in the . Example:

    1. const fp = require('fastify-plugin')
    2. async function myPlugin (app) {
    3. app.decorateRequest('foo', null)
    4. app.addHook('onRequest', async (req, reply) => {
    5. req.foo = { bar: 42 }
    6. })
    7. }
    8. module.exports = fp(myPlugin)

    See decorate for information about the dependencies parameter.

    decorateRequest(name, value, [dependencies])

    As above with decorateReply, this API is used add new methods/properties to the core Request object:

    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.

    1. // Don't do this
    2. fastify.decorateRequest('foo', { bar: 'fizz'})

    In this example, the reference of the object is shared with all the requests: any mutation will impact all requests, potentially creating security vulnerabilities or memory leaks.

    To achieve proper encapsulation across requests configure a new value for each incoming request in the . Example:

    See decorate for information about the dependencies parameter.

    hasDecorator(name)

    Used to check for the existence of a server instance decoration:

    1. fastify.hasDecorator('utility')

    hasRequestDecorator

    Used to check for the existence of a Request decoration:

    1. fastify.hasRequestDecorator('utility')

    hasReplyDecorator

    Used to check for the existence of a Reply decoration:

    1. fastify.hasReplyDecorator('utility')

    Defining a decorator (using decorate, decorateRequest, or ) with the same name more than once in the same encapsulated context 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. server.get('/', (req, reply) => {
    5. reply.view('/index.html', { hello: 'world' })
    6. })
    7. // Somewhere else in our codebase, we define another
    8. // view decorator. This throws.
    9. server.decorateReply('view', function (template, args) {
    10. // Another rendering engine
    11. })
    12. 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' })

    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: