Guide

Hooks

Learn how to use lifecycle hooks to customize SurrealDB connections

Hooks

Nuxt SurrealDB exposes a surrealHooks utility (auto-imported in both app and server contexts) powered by hookable. Use hooks to run logic when a SurrealDB connection is being established or has connected.

Available hooks

Client-side hooks

HookDescription
surrealdb:connectingCalled before connecting to the remote SurrealDB
surrealdb:connectedCalled after successfully connecting to the remote SurrealDB
surrealdb:memory:connectingCalled before connecting to the in-memory WASM engine
surrealdb:memory:connectedCalled after successfully connecting to the in-memory WASM engine
surrealdb:local:connectingCalled before connecting to the local WASM engine
surrealdb:local:connectedCalled after successfully connecting to the local WASM engine

Server-side hooks

In addition to all the hooks above, the server-side surrealHooks also provides:

HookDescription
surrealdb:session:initCalled when a new session is created for an H3Event
surrealdb:memory:session:initCalled when a new memory session is created for an H3Event
surrealdb:local:session:initCalled when a new local session is created for an H3Event

Usage in Nuxt plugins

Use hooks in a Nuxt plugin to run setup logic after a connection is established, for example to select a namespace and database or seed initial data:

plugins/surreal-setup.client.ts
export default defineNuxtPlugin(() => {
  surrealHooks.hook('surrealdb:memory:connected', async ({ client }) => {
    await client.use({
      namespace: 'test',
      database: 'test',
    })
    await client.query(
      'DEFINE TABLE IF NOT EXISTS test; UPSERT test SET name = "from-wasm-mem" WHERE name = "from-wasm-mem";',
    )
  })
})

Usage in Nitro plugins

Use hooks in a Nitro plugin for server-side initialization:

server/plugins/surreal-setup.ts
export default defineNitroPlugin(() => {
  surrealHooks.hook('surrealdb:memory:connected', async ({ client }) => {
    await client.use({
      namespace: 'test',
      database: 'test',
    })
    await client.query(
      'DEFINE TABLE IF NOT EXISTS test; UPSERT test SET name = "from-node-mem" WHERE name = "from-node-mem";',
    )
  })

  surrealHooks.hook('surrealdb:local:connected', async ({ client }) => {
    await client.use({
      namespace: 'test',
      database: 'test',
    })
    await client.query(
      'DEFINE TABLE IF NOT EXISTS test; UPSERT test SET name = "from-node-local" WHERE name = "from-node-local";',
    )
  })
})

Hook arguments

All connecting hooks receive { client, config }:

  • client — the Surreal instance being connected
  • config — the resolved connection configuration

All connected hooks receive { client }:

  • client — the connected Surreal instance

Session init hooks receive { session, event }:

  • session — the SurrealSession instance
  • event — the H3Event for the current request