Recipes

Hooks

Use lifecycle hooks to stay synced with NuxtHub.

onHubReady()

Use onHubReady() to ensure the execution of some code once NuxtHub environment bindings are set up.

onHubReady() is a shortcut using the hubHooks object under the hood to listen to the bindings:ready event.

This is useful to run database migrations inside your server/plugins/.

server/plugins/migrations.ts
export default defineNitroPlugin(() => {
  // Only run migrations in development
  if (import.meta.dev) {
    onHubReady(async () => {
      await hubDatabase().exec(`
        CREATE TABLE IF NOT EXISTS todos (
          id INTEGER PRIMARY KEY,
          title TEXT NOT NULL,
          completed INTEGER NOT NULL DEFAULT 0
        )
      `.replace(/\n/g, ''))
    })
  }
})

hubHooks

The hubHooks object is a collection of hooks that can be used to stay synced with NuxtHub.

Signature

Signature
export interface HubHooks {
  'bindings:ready': () => any | void
}

Usage

You can use the hubHooks object to listen to the bindings:ready event in your server plugins:

server/plugins/hub.ts
export default defineNitroPlugin(() => {
  hubHooks.hook('bindings:ready', () => {
    console.log('NuxtHub bindings are ready!')
    const db = hubDatabase()
  })
})
Note that hubHooks is a hookable instance.