In the above figure, there are several entities:

    1. The root context
    2. Three root plugins

    Given that everything in Fastify is a plugin, except for the root context, every “context” and “plugin” in this example is a plugin that can consist of decorators, hooks, plugins, and routes. Thus, to put this example into concrete terms, consider a basic scenario of a REST API server that has three routes: the first route () requires authentication, the second route (/two) does not, and the third route (/three) has access to the same context as the second route. Using to provide the authentication, the code for this example is as follows:

    The above server example shows all of the encapsulation concepts outlined in the original diagram:

    1. Only the authenticatedContext has access to the fastify-bearer-auth plugin.
    2. Both the publicContext and grandchildContext have access to the foo request decorator.
    3. Only the has access to the bar request decorator.

    Sharing Between Contexts

    Notice that each context in the prior example inherits only from the parent contexts. Parent contexts cannot access any entities within their descendent contexts. This default is occasionally not desired. In such cases, the encapsulation context can be broken through the usage of such that anything registered in a descendent context is available to the containing parent context.

    Assuming the publicContext needs access to the bar decorator defined within the grandchildContext in the previous example, the code can be rewritten to: