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
| Hook | Description |
|---|---|
surrealdb:connecting | Called before connecting to the remote SurrealDB |
surrealdb:connected | Called after successfully connecting to the remote SurrealDB |
surrealdb:memory:connecting | Called before connecting to the in-memory WASM engine |
surrealdb:memory:connected | Called after successfully connecting to the in-memory WASM engine |
surrealdb:local:connecting | Called before connecting to the local WASM engine |
surrealdb:local:connected | Called after successfully connecting to the local WASM engine |
Server-side hooks
In addition to all the hooks above, the server-side surrealHooks also provides:
| Hook | Description |
|---|---|
surrealdb:session:init | Called when a new session is created for an H3Event |
surrealdb:memory:session:init | Called when a new memory session is created for an H3Event |
surrealdb:local:session:init | Called 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— theSurrealinstance being connectedconfig— the resolved connection configuration
All connected hooks receive { client }:
client— the connectedSurrealinstance
Session init hooks receive { session, event }:
session— theSurrealSessioninstanceevent— the H3Event for the current request