Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Hooks and Lifecycle

Application Hooks: onReady, onClose, onRoute and Friends

Learn Fastify application hooks: onRoute, onRegister, onReady, onListen, preClose and onClose. Open and close database pools, inspect routes and clean up safely.

Request hooks run once per request. Application hooks run once per server life: when a route is registered, when a plugin is loaded, when the server is ready, and when it shuts down. They are where you open a database pool, warm a cache, check that required settings exist, and, at the end, close everything cleanly.

Getting this part right is the difference between a server that restarts smoothly and one that leaves connections hanging, logs half-finished writes, or hits "address in use" on the next deploy.

Fastify itself is not installed on this site; the examples run on the small stand-in described in The Fastify Request Lifecycle. It implements onRoute, onReady, onClose, decorate and register. The real framework has a few more hooks, listed in the table below.

The application hooks

Hook When it runs Typical use
onRoute Each time a route is added (synchronous) Inspect or modify route options, collect an API list
onRegister Each time a plugin creates a new encapsulated context (synchronous) Copy settings into the child scope
onReady After all plugins loaded, before the server starts accepting requests Verify dependencies, warm caches
onListen After the server started listening (real listen only) Log the address, notify a supervisor
preClose Start of close(), while the server still accepts work Stop background workers, signal "draining"
onClose End of close(), after connections finished Close database pools, flush logs

onRoute and onRegister are synchronous: they must not be async functions. The others may be async and are awaited in order.

JavaScript
// real Fastify
app.addHook('onRoute', (routeOptions) => {
  console.log('route added:', routeOptions.method, routeOptions.url);
});

app.addHook('onReady', async function () {
  await this.db.ping();          // `this` is the Fastify instance
});

app.addHook('onClose', async (instance) => {
  await instance.db.close();
});

onRoute: knowing your own API

onRoute receives the route options object. It fires inside the scope where the hook was added, so a plugin can watch only its own routes. A classic use is generating a route list for documentation or a startup log. You can even add a default to every route, such as a rate-limit setting or a schema tag.

Node.js onRoute: list and tweak routes as they register

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 two plugin routes appear with their full path, /api/users, because the hook receives the final URL including the prefix. The first two routes show that hooks added on the root instance see every route below it.

onReady: fail early, not on the first request

A server that boots but cannot reach its database is worse than one that refuses to start. onReady runs after all plugins finished loading and before traffic is accepted, so it is the right place for a connectivity check. If it throws, startup fails and your process manager reports the error immediately.

onClose: the other half of every resource

Anything you open at startup needs a matching onClose. The rule is: whoever opens it, closes it. Put both halves in the same plugin so they cannot drift apart:

JavaScript
// a plugin that owns a database pool (real Fastify)
import fp from 'fastify-plugin';

export default fp(async function dbPlugin(app, opts) {
  const pool = createPool(opts.url);
  app.decorate('db', pool);
  app.addHook('onClose', async () => { await pool.end(); });
});

The next example plays the whole story with a fake pool: connect while loading the plugin, check in onReady, serve a request, and close.

Node.js A resource that opens and closes with the app

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.

fp is the stand-in for the fastify-plugin wrapper. It makes the decorator db visible to the parent scope instead of hiding it inside the plugin's private context. The chapter on plugins and encapsulation in the Fastify tutorial explains why.

Order and scope

Application hooks follow the plugin tree:

  • Hooks registered on the root instance cover the whole app. Hooks registered inside a plugin cover that plugin's scope (for onRoute and onRegister).
  • onReady hooks run in the order they were added, which follows plugin load order. A plugin that depends on a decorator from another plugin must be registered after it.
  • Errors in onReady or onClose are not swallowed. A thrown error makes ready() or close() reject. Catch what you can survive (for example a failed cache warm-up) and log it.

A common mistake is to start long-running work in onReady and not await it. That hides startup errors. If you need background work (a polling job), start it in onReady and stop it in preClose or onClose, using an AbortController so the loop ends cleanly.

Checklist for resources

  1. Open the resource inside a plugin, not at module top level, so tests can build an app with a fake.
  2. Expose it with decorate, so handlers use this.db or app.db rather than a hidden global.
  3. Verify it in onReady if the app cannot work without it.
  4. Close it in onClose, and make that code safe to call twice.
  5. In tests, call await app.close() in an after hook so the process can exit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which application hooks are synchronous and must NOT be async functions?

    onRoute and onRegister run while routes and plugins are being registered, so they are plain synchronous functions. onReady, onListen, preClose and onClose may be async.
  2. 2. Where is the best place to verify that the database is reachable before accepting traffic?

    onReady runs once after all plugins are loaded and before the server accepts requests. If it throws, startup fails right away.
  3. 3. A plugin opens a connection pool. Which hook should close it?

    onClose runs when app.close() finishes. Opening and closing the resource in the same plugin keeps both halves together.
  4. 4. What does the onRoute hook receive?

    onRoute is called with the route options each time a route is added, letting you inspect or change them.

Summary

  • Application hooks run once per server life, not once per request.
  • onRoute and onRegister are synchronous; onReady, onListen, preClose and onClose can be async.
  • Use onReady to fail fast when a dependency is missing, and onClose to release every resource.
  • Open resources in plugins and expose them with decorate, so tests can swap them for fakes.
  • Do not leave background work unmanaged: start it in onReady, stop it in preClose or onClose.

Next: Request and Reply Hooks in Practice