# Nuxt Realtime - WebSockets and realtime state for Nuxt ::u-page-hero --- class: dark:bg-gradient-to-b from-neutral-900 to-neutral-950 orientation: horizontal --- :::prose-pre{filename="example.vue"} ```vue ``` ::: #top :hero-background #title Build [Realtime]{.text-primary} Experiences. #description Real-time state synchronization for Nuxt applications. Share reactive state across clients, broadcast events, and manage connections with a developer-friendly API. #links :::u-button --- size: xl to: https://nuxtrealtime.com/getting-started trailing-icon: i-lucide-arrow-right --- Get started ::: :::u-button --- size: xl target: _blank to: https://github.com/daanvangeloven/nuxt-realtime trailing-icon: i-simple-icons-github variant: outline --- View on GitHub ::: :: ::u-page-section --- class: dark:bg-neutral-950 --- #title Simple, Powerful Composables #features :::u-page-feature --- icon: i-lucide-refresh-cw --- #title Realtime State #description Share reactive state across all connected clients. **Works just like Vue's useState**, update the value and it syncs everywhere automatically. ::: :::u-page-feature --- icon: i-lucide-radio --- #title Realtime events #description Publish and subscribe to events across clients. Perfect for notifications, chat messages, or any real-time communication. ::: :::u-page-feature --- icon: i-lucide-wifi --- #title Realtime Connection #description Monitor connection status with reactive state. Handle connect, disconnect, and reconnection events with callbacks. ::: :::u-page-feature --- icon: i-lucide-plug --- #title Built on Socket.IO #description Reliable WebSocket connections with automatic reconnection, fallbacks to polling, and battle-tested performance. ::: :::u-page-feature --- icon: i-lucide-zap --- #title Optimistic Updates #description Instant UI feedback with automatic rollback on failure. Configure per-state for the best user experience. ::: :::u-page-feature --- icon: i-lucide-database --- #title Pluggable Storage #description Use memory, Redis, or any Nitro-supported storage driver for state persistence. Scale horizontally with shared storage backends. ::: :: ::u-page-section{.dark:bg-gradient-to-b.from-neutral-950.to-neutral-900} :::u-page-c-t-a --- links: - label: Get Started to: /getting-started trailingIcon: i-lucide-arrow-right - label: View on GitHub to: https://github.com/daanvangeloven/nuxt-realtime target: _blank variant: subtle icon: i-simple-icons-github class: dark:bg-neutral-950 description: Add real-time features to your Nuxt app in minutes. title: Ready to build realtime applications? --- :stars-bg ::: :: # Introduction Nuxt Realtime is a module that provides real-time state synchronization for Nuxt applications using Socket.IO. It allows you to share reactive state across all connected clients with a simple composable API. ## Features - **Real-time State Sync**: share reactive state across all connected clients automatically - **Pub/Sub Events**: broadcast events to other clients using publish/subscribe pattern - **Connection Management**: monitor connection status with reactive state and callbacks - **Optimistic Updates**: instant UI feedback with automatic rollback on failure - **Pluggable Storage**: use memory, Redis, or any Nitro-supported storage driver for persistence - **Built on Socket.IO**: reliable WebSocket connections with automatic reconnection ## Composables Nuxt Realtime provides three main composables: ::card-group :::card --- icon: i-lucide-refresh-cw title: useRealtimeState to: https://nuxtrealtime.com/composables/userealtimestate --- Share reactive state across all connected clients. Works just like Vue's useState. ::: :::card --- icon: i-lucide-radio title: useRealtimeEvents to: https://nuxtrealtime.com/composables/userealtimeevents --- Publish and subscribe to events across clients in real-time. ::: :::card --- icon: i-lucide-wifi title: useRealtimeConnection to: https://nuxtrealtime.com/composables/userealtimeconnection --- Monitor and control the WebSocket connection status. ::: :: ## Quick Example ```vue [app.vue] ``` # Installation ## Install with an AI agent Paste this into Claude Code, Codex, Cursor or another coding agent. It installs the module, wires it into your app and secures it. ```md Read and follow the instructions in https://raw.githubusercontent.com/daanvangeloven/nuxt-realtime/master/prompts/setup.md ``` To teach your agent the API for later work too, install the skill: ```bash npx skills add daanvangeloven/nuxt-realtime ``` ## Install the package ::code-group ```bash [pnpm] pnpm add nuxt-realtime ``` ```bash [npm] npm install nuxt-realtime ``` ```bash [yarn] yarn add nuxt-realtime ``` :: ## Add to your config Add `nuxt-realtime` to your modules and enable WebSocket support in Nitro: ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: ['nuxt-realtime'], nitro: { experimental: { websocket: true, }, }, }) ``` That's it. You can now use the realtime composables in your components. ::callout --- icon: i-lucide-settings to: https://nuxtrealtime.com/getting-started/configuration --- See the **Configuration** page to set up storage, Redis, Socket.IO options, and key cleanup. :: ## Requirements - Nuxt 3.x or Nuxt 4.x - Node.js 18+ - WebSocket support enabled in Nitro # Configuration All options are set under the `nuxtRealtime` key in `nuxt.config.ts`. | Option | Type | Default | Description | | ------------------------ | ------------------------------------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `auth` | `'required'` | unset | Refuse connections that no `nuxt-realtime:authenticate` hook identified, and make the gate hooks deny by default. See [Authentication](https://nuxtrealtime.com/#authentication). | | `storage` | Nitro storage mount | `{ driver: 'memory' }` | Where state is stored. Ignored when `redis` is set. See [Storage](https://nuxtrealtime.com/#storage). | | `redis` | `object` | unset | Redis connection for cross-server sync. See [Redis options](https://nuxtrealtime.com/#redis-options). | | `socketio.serverUrl` | `string` | same origin | URL of a separate realtime server for the client to connect to. | | `socketio.path` | `string` | `'/socket.io'` | Socket.IO path, shared by client and server. | | `socketio.serverOptions` | `ServerOptions` | unset | Passed to the Engine.IO server. See [Engine.IO Server Options](https://nuxtrealtime.com/#engineio-server-options). | | `limits` | `object` | see [Limits](https://nuxtrealtime.com/#limits) | Per-connection key length, value size, key count and event rate limits. | | `cleanup` | `object | false` | see [Key Cleanup](https://nuxtrealtime.com/#key-cleanup) | Lease-based removal of idle keys. `false` disables it. | | `lock.defaultTtl` | `number` (ms) | no expiry | TTL for a lock claim that sets none. See [TTL](https://nuxtrealtime.com/composables/userealtimelock#ttl-auto-release-after-a-timeout). | | `lock.staleGraceMs` | `number` (ms) | `10_000` | How long a disconnected client keeps its locks, presence and rooms before they are released. | | `instanceTimeoutMs` | `number` (ms) | `30_000` | How long an instance may stay silent before its connections are treated as disconnected. See [Instance timeout](https://nuxtrealtime.com/#instance-timeout). | | `logging.level` | `'debug' | 'info' | 'warn' | 'error' | 'silent'` | `'debug'` in dev, `'warn'` in production | Minimum log level. | | `logging.format` | `'pretty' | 'json'` | `'pretty'` | `'json'` writes newline-delimited JSON. | | `devtools` | `object | false` | `{}` | The DevTools tab, dev only. See [DevTools](https://nuxtrealtime.com/getting-started/devtools#configuration). | ## Storage Nuxt Realtime uses [Nitro's storage system](https://nitro.unjs.io/guide/storage){rel=""nofollow""} for state persistence. Configure it with the `storage` option. ### Memory (default) State is stored in-process and not shared between server instances. No extra configuration needed. ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { storage: { driver: 'memory', }, }, }) ``` ### Redis For persistent storage that survives server restarts. This does **not** sync state across multiple server instances (see [Cross-Server Sync](https://nuxtrealtime.com/#cross-server-sync) for that). Install `ioredis` as a peer dependency: ::code-group ```bash [pnpm] pnpm add ioredis ``` ```bash [npm] npm install ioredis ``` ```bash [yarn] yarn add ioredis ``` :: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { storage: { driver: 'redis', host: 'localhost', port: 6379, }, }, }) ``` ::callout{color="info" icon="i-lucide-info"} See the [Nitro storage documentation](https://nitro.unjs.io/guide/storage){rel=""nofollow""} for all available drivers and their options. :: ## Cross-Server Sync When running multiple server instances behind a load balancer, use the `redis` option to broadcast state changes across instances via Redis pub/sub. Every connected client sees up-to-date values regardless of which instance they are connected to. Install `ioredis` as a peer dependency: ::code-group ```bash [pnpm] pnpm add ioredis ``` ```bash [npm] npm install ioredis ``` ```bash [yarn] yarn add ioredis ``` :: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { redis: { host: 'localhost', port: 6379, }, }, }) ``` Or use a connection URL: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { redis: { url: process.env.REDIS_URL, }, }, }) ``` For Redis Cluster, use `cluster` instead: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { redis: { cluster: [{ host: 'redis-1', port: 6379 }, { host: 'redis-2', port: 6379 }], }, }, }) ``` ### Redis options | Option | Type | Description | | ---------------- | ---------------- | --------------------------------------------------------------------------------------------------- | | `host` | `string` | Redis host. Ignored when `url` is set. Defaults to `'localhost'`. | | `port` | `number` | Redis port. Ignored when `url` is set. Defaults to `6379`. | | `url` | `string` | Redis connection URL (e.g. `redis://localhost:6379`). Takes priority over `host`/`port`. | | `cluster` | `ClusterNode[]` | Cluster nodes. Takes priority over `url`/`host`/`port`. | | `clusterOptions` | `ClusterOptions` | Options passed to the ioredis cluster client (e.g. `redisOptions`, `scaleReads`). | | `password` | `string` | Redis password. Ignored when `cluster` is set — use `clusterOptions.redisOptions.password` instead. | | `db` | `number` | Redis database index. | | `tls` | `object` | TLS options passed to ioredis. | | `base` | `string` | Key prefix for all stored values. | ::callout{color="warning" icon="i-lucide-triangle-alert"} The `redis` and `storage` options are mutually exclusive. When both are set, `redis` takes precedence. :: ## Engine.IO Server Options Pass options to the underlying Engine.IO server via `socketio.serverOptions`. These map to `engine.io`'s `ServerOptions` (Socket.IO transport-layer options). ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { socketio: { serverUrl: 'https://realtime.example.com', serverOptions: { cors: { origin: ['https://myapp.com'], credentials: true, }, maxHttpBufferSize: 1e6, // 1 MB }, }, }, }) ``` ::callout{color="info" icon="i-lucide-info"} CORS is only needed when `socketio.serverUrl` points at a different origin than your app. Same-origin connections work without it. :: ### Origin check Browsers always send an `Origin` header on WebSocket connections, so the server uses it to block cross-site hijacking. Without `cors.origin` only same-origin connections are accepted (the `X-Forwarded-Host` header is honored behind a proxy). With `cors.origin` set, only the listed origins are accepted. Requests without an `Origin` header, such as server-side or native clients, are always accepted. To take over the check entirely, set your own `serverOptions.allowRequest`. ## Limits Each connection is limited so one client cannot exhaust server memory or storage. All values can be overridden: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { limits: { maxKeyLength: 256, // storage keys, lock keys, room ids, event channels maxValueBytes: 262_144, // JSON size of a storage value, lock ownerInfo, presence info, event data maxKeysPerSocket: 1000, // subscribed rooms and distinct storage keys written, per connection maxEventsPerSecond: 120, // 0 disables; excess events are dropped }, }, }) ``` ## Authentication Set `auth: 'required'` to refuse every connection that no `nuxt-realtime:authenticate` hook identified. The check runs before the transport opens. With it set, the gate hooks below deny by default and presence `info` and lock `ownerInfo` stay `null` until a `nuxt-realtime:publicInfo` hook sets them. ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { auth: 'required', }, }) ``` Leave it unset to keep accepting anonymous connections. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app) for the hooks. ## Authorizing reads and writes Unless you say otherwise, every client can subscribe to any event channel (including the `event:*` wildcards), any lock and any state key, and can write any non-reserved key. Register these Nitro hooks to restrict that. `canJoinRoom`, `canSubscribe`, `canPublish` and `canWrite` allow by default, or deny when `auth` is `'required'`. Each hook votes on its own: any deny wins, then any allow, then the default. A hook that throws denies: ```ts [server/plugins/realtime-auth.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canSubscribe', (ctx) => { // ctx.kind is 'event' or 'lock'; ctx.name is the channel or lock key if (ctx.kind === 'event') ctx.allow = !ctx.name.startsWith('admin:') && ctx.name !== '*' }) nitroApp.hooks.hook('nuxt-realtime:canPublish', (ctx) => { ctx.allow = ctx.channel.startsWith('chat:') }) nitroApp.hooks.hook('nuxt-realtime:canWrite', (ctx) => { // ctx.key is the normalized state key, ctx.value the new value ctx.allow = ctx.key.startsWith('shared:') }) }) ``` `ctx.kind` is also `'state'` for `storage:get` and `storage:subscribe`. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app#gate-hooks) for every gate. ## Instance timeout With Redis, each server instance writes a liveness timestamp on every sweep tick. When an instance is silent for longer than `instanceTimeoutMs`, its connections are treated as disconnected. After `lock.staleGraceMs` their locks, presence and room membership are released. ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { instanceTimeoutMs: 30_000, // default }, }) ``` Keep it well above the sweep interval, which is `lock.staleGraceMs / 3` and at least 1 second. ## Key Cleanup Nuxt Realtime automatically removes unused storage keys through a lease-based cleanup system. When no client has subscribed to a key for longer than the idle threshold, the key is deleted. This is enabled by default with sensible defaults: | Option | Default | Description | | ------------------- | -------------- | ----------------------------------------------------------- | | `heartbeatInterval` | `30_000` ms | How often clients send a heartbeat to keep their keys alive | | `cleanupInterval` | `300_000` ms | How often the server scans for and removes expired keys | | `idleThreshold` | `3_600_000` ms | How long a key must be idle before it is removed | ### Customizing cleanup ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { cleanup: { heartbeatInterval: 30_000, // 30s cleanupInterval: 300_000, // 5 min idleThreshold: 3_600_000, // 1 hour }, }, }) ``` ### Disabling cleanup Set `cleanup: false` to opt out entirely. Useful when you manage storage lifecycle yourself or your storage driver handles expiry natively (e.g. Redis TTLs). ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { cleanup: false, }, }) ``` # Usage Nuxt Realtime provides three main composables for building real-time applications. This page gives a quick overview; see the individual composable pages for full API documentation. ## useRealtimeState Share reactive state across all connected clients. Works just like Vue's `useState` but syncs automatically. ```vue ``` ::callout --- icon: i-lucide-arrow-right to: https://nuxtrealtime.com/composables/userealtimestate --- See the full **useRealtimeState** documentation for options, return values, and more examples. :: --- ## useRealtimeEvents Publish and subscribe to events across clients. Perfect for notifications, chat messages, or any ephemeral real-time communication. ```vue ``` ::callout --- icon: i-lucide-arrow-right to: https://nuxtrealtime.com/composables/userealtimeevents --- See the full **useRealtimeEvents** documentation for subscribe options, typing, and more examples. :: --- ## useRealtimeConnection Monitor and control the WebSocket connection status. ```vue ``` ::callout --- icon: i-lucide-arrow-right to: https://nuxtrealtime.com/composables/userealtimeconnection --- See the full **useRealtimeConnection** documentation for all callbacks and manual control methods. :: --- While developing, open Nuxt DevTools and check the **Realtime** tab to see active connections, subscribed channels/storage keys, live storage values, and a scrolling event log. See [DevTools](https://nuxtrealtime.com/getting-started/devtools) for details. --- ## Putting It All Together Here's a complete example combining all three composables: ```vue [app.vue] ``` # Authentication Nuxt Realtime authenticates connections in the `nuxt-realtime:authenticate` Nitro hook, before the transport opens. Set `auth: 'required'` to refuse every connection that the hook did not identify. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app) for the full setup, including the gate hooks and a cookie or token example. The Socket.IO `Server` instance is also exposed through the `nuxt-realtime:io` hook. This page covers `io.use()` middleware, which is useful when you want Socket.IO's own handshake `auth` payload or extra checks on top of `authenticate`. ::callout{color="info" icon="i-lucide-info"} `io.use()` middleware runs after the transport has opened, so a rejection arrives as a Socket.IO connect error and not as a refused connection. Use `nuxt-realtime:authenticate` when the connection should never open. :: ## io.use() middleware Create a Nitro server plugin and hook into `nuxt-realtime:io`. The hook fires after the `Server` is configured but before it is bound to the transport and before `connection` handlers are wired up, so every `io.use()` middleware registered here runs for every incoming connection. ```ts [server/plugins/realtime-auth.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:io', (io) => { io.use((socket, next) => { // authenticate here: call next() to allow, next(new Error(...)) to reject next() }) }) }) ``` ## JWT-based authentication Nuxt Realtime creates the client socket for you, so you can't call `io({ auth: ... })` directly. Instead, register a `nuxt-realtime:auth` app hook. It fires before every connection attempt, including reconnects, so you can supply a fresh token each time instead of baking one in at initial connect: ```ts [plugins/realtime-auth.client.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('nuxt-realtime:auth', (ctx) => { ctx.auth.token = useAuthToken().value }) }) ``` For a token that expires and needs refreshing on reconnect, fetch it inside the hook instead of reading a cached value: ```ts [plugins/realtime-auth.client.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('nuxt-realtime:auth', async (ctx) => { ctx.auth.token = await fetchFreshToken() }) }) ``` Verify it on the server: ```ts [server/plugins/realtime-auth.ts] import jwt from 'jsonwebtoken' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:io', (io) => { io.use((socket, next) => { const token = socket.handshake.auth?.token if (!token) return next(new Error('Unauthorized')) try { const payload = jwt.verify(token, process.env.JWT_SECRET!) socket.data.user = payload next() } catch { next(new Error('Unauthorized')) } }) }) }) ``` The middleware rejects unauthenticated connections before a `connection` event is ever emitted. The module sets `socket.data.user` from `nuxt-realtime:authenticate` before your middleware runs, so you can read it there instead of parsing the token again. `ctx.auth` reaches the server at Socket.IO connect time, after the transport opened. To send a value that `nuxt-realtime:authenticate` can check up front, set `ctx.query` in the same client hook. ## Session / cookie-based authentication Read the session cookie from the underlying HTTP request exposed via `socket.request`: ```ts [server/plugins/realtime-auth.ts] import { parse } from 'cookie' import { unsealData } from 'iron-session' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:io', (io) => { io.use(async (socket, next) => { const cookies = parse(socket.request.headers.cookie ?? '') const sessionCookie = cookies['session'] if (!sessionCookie) return next(new Error('Unauthorized')) try { const session = await unsealData(sessionCookie, { password: process.env.SESSION_SECRET! }) socket.data.user = session.user next() } catch { next(new Error('Unauthorized')) } }) }) }) ``` ## Gating channels with `socket.data` ::callout{color="info" icon="i-lucide-info"} `event:subscribe` and `event:publish` (used by [`useRealtimeEvents`](https://nuxtrealtime.com/composables/userealtimeevents)) are gated by the `canSubscribe` and `canPublish` hooks. A handler you register for the same event name with `socket.on()` runs alongside the built-in one and cannot block it. Use the [gate hooks](https://nuxtrealtime.com/getting-started/securing-your-app#gate-hooks) to restrict the built-in events. :: For your own custom events, use `socket.data.user` in the handler, or call `guard()` to get the same rate limit, size limit and gate hooks as the built-in events: ```ts [server/plugins/realtime-channel-guard.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:io', (io) => { io.on('connection', (socket) => { socket.on('room:join', (channel: string) => { const user = socket.data.user if (!canAccessChannel(user, channel)) { socket.emit('error', { message: 'Forbidden' }) return } socket.join(`room:${channel}`) }) }) }) }) ``` ::callout{color="info" icon="i-lucide-info"} `socket.data` is typed as `any` by default. You can narrow it by extending Socket.IO's `SocketData` interface in a type definition file in your project. :: ## Reconnect identity Each browser tab gets a `connectionId` that survives reconnects, so locks, presence and room membership are kept for a grace period after a disconnect. That id is visible to other clients (it is the lock and presence owner), so it is not a credential. The server issues a per-connection secret the first time an id is seen, the client stores it, and the id can only be reclaimed by presenting it. A client that loses its secret reconnects with a fresh identity. To tie identity to a logged-in user instead, rebind `connectionId` to a verified value in `nuxt-realtime:identify`. The hook also gets `ctx.user` and `ctx.reject(reason?)`, which disconnects the socket. # Securing your app ::callout{icon="i-lucide-shield-check"} Read the [known limits](https://nuxtrealtime.com/#known-limits) before you expose it to real users. :: By default the realtime server accepts any connection and lets it read and write any non-reserved key. That is fine for a prototype. For a real app, turn on required authentication. Then every connection has a verified user, and every read, write and join goes through a hook you control. ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { auth: 'required', }, }) ``` With `auth: 'required'`: - A connection that no `nuxt-realtime:authenticate` hook identified is refused before the transport opens. - The gates (`canJoinRoom`, `canSubscribe`, `canPublish`, `canWrite`) deny by default. You allow what you want in hooks. - Presence `info` and lock `ownerInfo` are `null` unless a `nuxt-realtime:publicInfo` hook sets them. ## Authenticate connections Register the `nuxt-realtime:authenticate` Nitro hook and set `ctx.user` to the verified user. ```ts interface AuthenticateContext { event: H3Event req: IncomingMessage transport: 'polling' | 'websocket' user: unknown reject: (reason?: string) => void } ``` The hook runs before the connection opens. For the polling transport it runs on the Engine.IO handshake. For WebSocket it runs on the upgrade request, before the server answers `101`. A connection is refused when: - a hook calls `ctx.reject()`, - a hook throws, or - `auth` is `'required'` and `ctx.user` is still empty after all hooks ran. A refused polling handshake gets a `403` and no session id. A refused WebSocket upgrade gets a `401` (a disallowed origin gets a `403`). In both cases the socket never opens. The hook can run twice for one connection: once for the polling handshake and once when the client upgrades to WebSocket. Keep it fast and free of side effects. The socket keeps the user from the handshake. ### Cookie or session `ctx.event` is an h3 event built from the request, so h3's read helpers work: `getCookie`, `getHeader`, `getQuery` and `getSession`/`useSession`. Write helpers such as `setCookie` have no effect, because there is no real response at this point. ```ts [server/plugins/realtime-authenticate.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:authenticate', async (ctx) => { const session = await getSession<{ user?: { id: string, name: string } }>(ctx.event, { password: process.env.SESSION_SECRET!, }) ctx.user = session.data.user }) }) ``` A request without a session gives an empty session, not an error, so `ctx.user` stays empty and `auth: 'required'` refuses it. If you use `nuxt-auth-utils`, its `getUserSession(ctx.event)` is built on the same h3 session helper. Only the h3 helpers themselves are covered by this module's tests. ### Token in the query A browser WebSocket cannot send custom headers, and cookies do not cross origins. Send a token in the handshake query instead. The client side is the `nuxt-realtime:auth` hook, where `ctx.query` becomes the Engine.IO handshake query: ```ts [plugins/realtime-auth.client.ts] export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('nuxt-realtime:auth', async (ctx) => { ctx.query.token = await fetchRealtimeToken() }) }) ``` On the server, read it with `getQuery` and verify it: ```ts [server/plugins/realtime-authenticate.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:authenticate', async (ctx) => { const { token } = getQuery(ctx.event) if (typeof token !== 'string') return ctx.reject('Missing token') ctx.user = await verifyRealtimeToken(token) }) }) ``` ::callout{color="info" icon="i-lucide-info"} `ctx.auth` is sent at Socket.IO connect time, after the transport is already open. It is too late for `authenticate`. Use `ctx.query` for anything the server must check up front. On a reconnect the query is one attempt behind: the hook runs for the next attempt, so the first retry sends the value from the previous run. :: The client connects after the `nuxt-realtime:auth` hook has finished, so the first attempt always carries the query. ## Identity is owned by the server The verified user lives in `socket.data.user`. The module sets it before your `nuxt-realtime:io` middleware runs, so every hook and `io.use()` middleware sees it. With `auth: 'required'`, a socket whose user an app middleware cleared is disconnected. No client-supplied field can set the user, the connection owner or lock ownership. A `user`, `owner`, `ownerInfo` or `connectionId` inside a payload is treated as plain data. `socket.data.user` is typed as `any`. Narrow it by extending Socket.IO's `SocketData` interface. The `connectionId` is a reconnect handle, not a credential. See [Reconnect identity](https://nuxtrealtime.com/getting-started/authentication#reconnect-identity). To refuse a socket after you looked up more about it, use the `nuxt-realtime:identify` hook, which has `ctx.user` and `ctx.reject(reason?)`. `identify` runs for every socket; `ctx.connectionId` is `socket.id` when the client sent none. No socket handler runs until it has finished, and messages from a rejected socket are dropped. ## Gate hooks Five hooks decide what a connection may do. Register them in a Nitro plugin. | Hook | Runs on | Default | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `nuxt-realtime:canJoinRoom` | every explicit join: `room:join`, `presence:join`, `presence:subscribeRoom`, `lock:subscribeRoom` | allow, deny with `auth: 'required'` | | `nuxt-realtime:canSubscribe` | `event:subscribe`, `lock:subscribe`, every `lock:claim` (with a `room`, `canJoinRoom` must allow too), and state reads: `storage:get`, `storage:subscribe` | allow, deny with `auth: 'required'` | | `nuxt-realtime:canPublish` | `event:publish` | allow, deny with `auth: 'required'` | | `nuxt-realtime:canWrite` | `storage:set` | allow, deny with `auth: 'required'` | | `nuxt-realtime:canForceRelease` | `lock:forceRelease` | always deny | Every gate context has `user` and `socket` next to its own fields: ```ts interface GateContext { user: unknown socket: Socket deny: (reason?: string) => void allow?: boolean // starts undefined } // canJoinRoom: { roomId, connectionId } // canSubscribe: { kind: 'event' | 'lock' | 'state', name, connectionId } // canPublish: { channel, data, connectionId } // canWrite: { key, value, connectionId } // key is normalized // canForceRelease: { key, connectionId, currentOwner } ``` ```ts [server/plugins/realtime-gates.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canWrite', (ctx) => { const user = ctx.user as { id: string } // clients may only write keys under their own user id if (ctx.key.startsWith(`user:${user.id}:`)) ctx.allow = true else ctx.deny('Not your key') }) nitroApp.hooks.hook('nuxt-realtime:canSubscribe', (ctx) => { // `*` also receives admin: events, so it is denied too if (ctx.kind === 'event' && (ctx.name.startsWith('admin:') || ctx.name === '*')) ctx.deny('Admins only') else ctx.allow = true }) }) ``` `canWrite` runs after the cheap checks (reserved key, size, key count) and before the value is stored. A denied write stores and broadcasts nothing. The deny reason comes back to the client in the error acknowledgement, for example `{ success: false, error: 'Not your key' }`. A denied `storage:get` returns `null`. ### How hooks combine Each registered hook runs with its own copy of the context and casts one vote: - `ctx.deny(reason)` or `ctx.allow = false` is a deny. - `ctx.allow = true` is an allow. - Setting nothing is an abstain. - A hook that throws is a deny, with the reason `Hook error`. Any deny wins. Otherwise any allow wins. If every hook abstains (or none is registered), the default applies. So a later hook can never undo an earlier deny, and registration order does not matter. With `auth: 'required'` and no hooks, everything is denied until you write one. ### Re-checking joins `canJoinRoom` runs on every explicit join, not only the first one per connection. Clients join again after a reconnect, so a permission you revoke takes effect then. `lock:claim` with a `room` reuses the allow from the socket's earlier join instead of asking again. ## Presence and lock info Presence `info` and lock `ownerInfo` are shown to other clients. The `nuxt-realtime:publicInfo` hook decides what is stored and broadcast. The client's value arrives only as `ctx.clientInfo`, which you should treat as untrusted. ```ts [server/plugins/realtime-project.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:publicInfo', (ctx) => { const user = ctx.user as { name: string, avatarUrl: string } ctx.info = { name: user.name, avatarUrl: user.avatarUrl } }) }) ``` ```ts interface ProjectContext { kind: 'presence' | 'lock' room?: string key?: string // lock key user: unknown connectionId: string socket: Socket clientInfo: unknown info: unknown // set this } ``` `ctx.info` starts as `null` with `auth: 'required'`, and as `clientInfo` otherwise. Unlike the gates, these hooks run in registration order on one shared context, and each can change what the previous one set. If a hook throws, `info` becomes `null`. The projected value is what gets stored, so late joiners see the same data as live broadcasts. Not projected: `lock:release` `meta`, state values and event data are still client data. Gate them with `canWrite` and `canPublish`. ## Extending the server Server code can reuse the module's own checks and write to realtime state. Both functions are Nitro auto-imports, also inside server plugins of other modules. ### guard() Use `guard()` in a custom socket event to apply what the built-in handlers apply: the socket's rate limit, key validity, size limit, the wait for identification, and the matching gate hook. It returns a decision and leaves the work to your handler. ```ts function guard( socket: Socket, options: { kind: 'write' | 'publish' | 'subscribe' | 'join', name: string, data?: unknown }, ): Promise<{ allowed: boolean, reason?: string }> ``` | `kind` | Gate hook it runs | | ----------- | -------------------------------------------------------- | | `write` | `canWrite` (`name` is the key, `data` the value) | | `publish` | `canPublish` (`name` is the channel, `data` the payload) | | `subscribe` | `canSubscribe` with `kind: 'event'` | | `join` | `canJoinRoom` (`name` is the room id) | `guard()` does not check room capacity. ### useRealtimeServer() Trusted server-side access, with no gate hooks: ```ts function useRealtimeServer(): { publish: (channel: string, data?: unknown) => Promise getState: (key: string) => Promise setState: (key: string, value: StorageValue) => Promise } ``` Keys are still validated: reserved (`_`-prefixed) and malformed keys throw. With Redis, writes and publishes reach clients on other instances. It throws if called while Nitro plugins are still loading, so call it from a request handler or a hook. ```ts [server/api/announce.post.ts] export default defineEventHandler(async (event) => { const { text } = await readBody(event) await useRealtimeServer().publish('announcements', text) return { ok: true } }) ``` ### After hooks `nuxt-realtime:afterWrite` and `nuxt-realtime:afterPublish` fire after a write or publish succeeded, from clients and from `useRealtimeServer()`: ```ts interface AfterWriteContext { key: string value: unknown connectionId?: string // client source only socket?: Socket // client source only user?: unknown // client source only source: 'client' | 'server' } // afterPublish has { channel, data } instead of { key, value } ``` They never fire for a denied or failed call. They are not awaited before the client's acknowledgement, and a throwing hook is only logged. Use them for audit logs, history and webhooks. ## Writing a plugin package A package that extends Nuxt Realtime is a Nuxt module. The module adds a Nitro server plugin. The plugin registers hooks and uses `guard()` and `useRealtimeServer()`. Its configuration goes through the package's own module options, not through `nuxtRealtime`. The playground has a small example in `playground/server/plugins/realtime-max-payload.ts`. It adds a custom `announce` event that gets the same rate limit, size limit and `canPublish` check as `event:publish`, and logs through `afterPublish`: ```ts [playground/server/plugins/realtime-max-payload.ts] import type { Server } from 'socket.io' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:io', (io: Server) => { io.on('connection', (socket) => { socket.on('announce', async (text: string, ack?: (r: unknown) => void) => { const verdict = await guard(socket, { kind: 'publish', name: 'announcements', data: text }) if (!verdict.allowed) return ack?.({ success: false, error: verdict.reason }) await useRealtimeServer().publish('announcements', text) ack?.({ success: true }) }) }) }) nitroApp.hooks.hook('nuxt-realtime:afterPublish', (ctx) => { console.log(`[realtime] ${ctx.source} published on ${ctx.channel}`) }) }) ``` As a package, wrap it in a module that passes its options to the plugin through runtime config: ```ts [src/module.ts] import { defineNuxtModule, createResolver, addServerPlugin } from '@nuxt/kit' export interface ModuleOptions { maxLength?: number } export default defineNuxtModule({ meta: { name: 'realtime-announcements', configKey: 'realtimeAnnouncements' }, defaults: { maxLength: 500 }, setup(options, nuxt) { const { resolve } = createResolver(import.meta.url) nuxt.options.runtimeConfig.realtimeAnnouncements = { maxLength: options.maxLength } addServerPlugin(resolve('./runtime/server/plugins/announce')) }, }) ``` ```ts [src/runtime/server/plugins/announce.ts] export default defineNitroPlugin((nitroApp) => { const { maxLength } = useRuntimeConfig().realtimeAnnouncements as { maxLength: number } nitroApp.hooks.hook('nuxt-realtime:io', (io) => { io.on('connection', (socket) => { socket.on('announce', async (text: string, ack?: (r: unknown) => void) => { if (typeof text !== 'string' || text.length > maxLength) return ack?.({ success: false, error: 'Too long' }) const verdict = await guard(socket, { kind: 'publish', name: 'announcements', data: text }) if (!verdict.allowed) return ack?.({ success: false, error: verdict.reason }) await useRealtimeServer().publish('announcements', text) ack?.({ success: true }) }) }) }) }) ``` The app that installs the package still owns the policy. With `auth: 'required'`, `announce` is denied until the app registers a `canPublish` hook that allows `announcements`. ## Multi-instance notes - Presence, locks and rooms live in storage, so all instances must share it. Set the `redis` option. - Presence and lock changes are relayed over the module's pub/sub (the `nuxt-realtime:broadcast` channel), so a client on instance B sees a change made through instance A. This still uses two Redis connections per instance. - Engine.IO polling keeps its session in memory on one instance. Use sticky sessions at your load balancer, or set `socketio.serverOptions.transports` to `['websocket']`. This comes from Engine.IO and has not been tested with this module. - Each instance writes a liveness timestamp on every sweep tick. If an instance is silent for longer than `instanceTimeoutMs` (default 30 seconds), its connections are marked stale. After `lock.staleGraceMs` their locks, presence and room membership are released and broadcast, so a crashed instance does not leave them behind. - The transport depends on crossws's Node adapter internals, so it only runs on Node. See [Multi-Server Sync](https://nuxtrealtime.com/technical/cross-server-sync) for how state and events travel. ## Running the realtime server on its own The `socketio.serverUrl` option already points the client at a separate server. The design for a standalone deployment (for example the realtime server on Railway and the Nuxt app on Vercel) uses the pieces above, with no JWT library built in: 1. The Nuxt app issues a short-lived token (for example a JWT) for the logged-in user. 2. The client sends it in `nuxt-realtime:auth` as `ctx.query.token`, so it arrives with the handshake. 3. The realtime server verifies it in `nuxt-realtime:authenticate` with a library you pick, and copies the claims to `ctx.user`. 4. Set `socketio.serverOptions.cors.origin` to the origin of the Nuxt app. Cookies from the app's origin do not reach another origin, so use the token rather than a session cookie. Because the query is one attempt behind on reconnect, keep the token lifetime longer than a reconnect cycle, or accept one failed retry. ## Not built in These features are not shipped. Each has a seam you can build on today. ### Schema validation Validate `ctx.value` in `canWrite` and `ctx.data` in `canPublish`, and call `ctx.deny('Invalid')`. For custom events, validate before `guard()` or inside the handler. ### Extra rate limits The built-in limit is per connection and per second. Add per-user or per-key limits in a gate hook, or call your own counter before `guard()` in a custom event. ### Lock ownership rules Restrict who may claim a lock with `canSubscribe` (`kind: 'lock'`), and who may take it over with `canForceRelease`, which has `user` and `currentOwner`. ### History and replay Record events in `afterPublish` and state changes in `afterWrite`, store them yourself, and replay with `useRealtimeServer().publish`. ### Atomic increment or compare-and-set `storage:set` is last write wins. Add a custom event, gate it with `guard({ kind: 'write' })`, and do the read-modify-write in your own code with `useRealtimeServer()`. It is only atomic on one instance unless your storage supports it. ### Yjs provider Add custom events for the Yjs sync messages, gate them with `guard()`, and persist updates from `afterPublish` or your own handler. ### Hosted multi-tenant Isolating tenants means prefixing keys and channels per tenant. Do it in `authenticate` (put the tenant in `ctx.user`) and enforce the prefix in each gate hook. ### Durable Objects or other runtimes The Node-only part is `src/runtime/server/utils/transport.ts`. A new adapter would replace it, and cross-instance messaging would need another `PubSubDriver`. ## Known limits - A denied `canJoinRoom` mid-session only removes the socket from the `room:` channel. Presence and lock-room channels it joined earlier stay until it reconnects. - A client that reconnects to another instance within about `instanceTimeoutMs` of a crash cannot reclaim its `connectionId` and gets a fresh one. Its old locks are released by a later sweep. - `lock:release` `meta`, state values and event data are client data and reach other clients as sent. Gate them with hooks. - `storage:subscribe` and `event:subscribe` accept an optional acknowledgement with `{ success, error? }`, but the built-in composables do not use it yet. A denied subscribe is silent in the UI. - Polling with sticky sessions, and the multi-instance flows behind a real load balancer, have not been tested. - The transport is Node only. - The module does not verify tokens or sessions. `socket.data.user` is whatever your `authenticate` hook sets. ## Behavior changes These apply even with `auth` unset: 1. A cross-origin WebSocket gets a `403` before the upgrade. Before, it got `101` and was closed with code 1008. 2. Gate hooks vote. `ctx.allow = true` can no longer undo another hook's deny, and `ctx.allow` starts as `undefined` inside a hook. 3. `canJoinRoom` runs on every explicit join. 4. With Redis, presence and lock changes reach clients on other instances. 5. `useRealtimePresence().join()` resolves a `boolean`. 6. A registered `authenticate` hook that rejects refuses the connection, even with `auth` unset. 7. No socket handler runs before `identify` has finished. Messages dropped by the rate limit or a rejected socket now answer an acknowledgement with a failure instead of leaving the call hanging. # DevTools Nuxt Realtime adds a "Realtime" tab to [Nuxt DevTools](https://devtools.nuxt.com/){rel=""nofollow""} showing what's happening on the wire while you develop: active connections, subscribed channels and storage keys per socket, live storage values, and a scrolling event log. It's dev-only: the tab, its backing route, and the event log are never present in production builds. ## What it shows - **Connections**: every currently connected socket, its address, transport, and how long it's been connected. - **Channels & storage keys**: per connection, which `useRealtimeEvents` channels and `useRealtimeState`/`useRealtimeConnection` storage keys it's subscribed to. - **Storage**: every key currently in the `nuxt-realtime` storage mount, its value, and how many sockets are subscribed to it. - **Event log**: a scrolling, in-memory log of `connect`, `disconnect`, `event:subscribe`/`unsubscribe`/`publish`, and `storage:subscribe`/`unsubscribe`/`set`. The log never includes payload/value bodies, only channel/key names, so it can't leak arbitrary application data. ::callout{color="warning" icon="i-lucide-triangle-alert"} The storage snapshot shown in the tab is served by an unauthenticated dev-only HTTP route. This is fine on a local dev server, but don't put secrets in `nuxt-realtime` storage. :: ## Configuration The tab is on by default whenever your app is running in dev mode. Configure the event log size, or turn it off entirely, via the `devtools` option: ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: ['nuxt-realtime'], nuxtRealtime: { devtools: { eventLogSize: 500, // default: 200 }, // or: devtools: false } }) ``` # useRealtimeState Share reactive state across all connected clients. Works just like Vue's `useState` but automatically synchronizes changes in real-time. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeState( key: string, defaultValue?: T, options?: UseRealtimeStateOptions ): UseRealtimeStateReturn ``` ## Parameters ### key - **Type:** `string` - **Required:** Yes A unique identifier for the state. All clients using the same key will share the same state. ```ts // Different keys = different state const counter = useRealtimeState('counter', 0) const users = useRealtimeState('online-users', []) const settings = useRealtimeState('app-settings', { theme: 'dark' }) ``` ### defaultValue - **Type:** `T` - **Required:** No The initial value to use if no state exists on the server. If the server already has a value for this key, that value will be used instead. ```ts // Primitives const count = useRealtimeState('count', 0) const name = useRealtimeState('name', 'Anonymous') const enabled = useRealtimeState('enabled', true) // Objects const profile = useRealtimeState('profile', { name: 'User', avatar: '/default.png', }) // Arrays const messages = useRealtimeState('messages', []) ``` ### options - **Type:** `UseRealtimeStateOptions` - **Required:** No ```ts interface UseRealtimeStateOptions { /** * Whether to optimistically update the value before server confirmation. * Only applies to `immediate` and `debounced` strategies. * @default true */ optimisticUpdates?: boolean /** * Timeout for server operations in milliseconds. * @default 5000 */ updateTimeout?: number /** * Sync strategy to use. * - `immediate`: every change syncs to the server right away (default) * - `debounced`: buffers rapid changes and syncs after `debounceMs` of inactivity * - `manual`: local-only changes until `sync()` is called explicitly * @default 'immediate' */ sync?: 'immediate' | 'debounced' | 'manual' /** * Debounce delay in milliseconds. Only used when `sync` is `'debounced'`. * @default 300 */ debounceMs?: number } ``` ## Return Value Returns a `WritableComputedRef` with additional properties: ```ts interface UseRealtimeStateReturn extends WritableComputedRef { /** True while fetching the initial value from the server */ loading: Readonly> /** Manually fetch the latest value from the server */ refresh: () => void /** True when there are local changes not yet synced to the server */ isDirty: Readonly> /** Explicitly push the current local value to the server */ sync: () => void } ``` ### value Access and update the state value: ```ts const counter = useRealtimeState('counter', 0) // Read console.log(counter.value) // 0 // Write (syncs to all clients) counter.value = 10 counter.value++ ``` ### loading A readonly ref that is `true` while the initial value is being fetched from the server: ```vue ``` ### refresh() Manually fetch the latest value from the server: ```ts const counter = useRealtimeState('counter', 0) // Force refresh from server counter.refresh() ``` ### isDirty A readonly reactive flag that is `true` when the local value has been changed but not yet synced to the server. Most useful with the `manual` strategy. ```ts const draft = useRealtimeState('doc', '', { sync: 'manual' }) draft.value = 'Hello' console.log(draft.isDirty.value) // true await draft.sync() console.log(draft.isDirty.value) // false ``` ### sync() Explicitly push the current local value to the server. Intended for the `manual` strategy but callable on any strategy. ```ts const draft = useRealtimeState('doc', '', { sync: 'manual' }) draft.value = 'Some content' // Later, when the user clicks Save: draft.sync() ``` ## Sync Strategies ### immediate (default) Every assignment syncs to the server immediately. This is the simplest option and works well for low-frequency updates. ```ts const status = useRealtimeState('status', 'idle') // Syncs to server instantly status.value = 'active' ``` With optimistic updates enabled (the default), the local value updates right away. If the server rejects the change, the value is automatically rolled back. ### debounced Rapid changes are buffered locally and only sent to the server after a configurable period of inactivity. The timer resets each time the value changes, so only the final value in a burst is transmitted. Ideal for text inputs, sliders, and any scenario where users make many rapid changes. ```ts const query = useRealtimeState('search-query', '', { sync: 'debounced', debounceMs: 400, }) // These three changes are batched: only 'baz' is sent to the server query.value = 'foo' query.value = 'bar' query.value = 'baz' ``` ### manual Changes are kept local until `sync()` is called explicitly. The `isDirty` flag tracks whether unsaved changes exist. Use this for forms or documents where the user controls when to save. ```ts const doc = useRealtimeState('document', '', { sync: 'manual' }) // Only updates locally: nothing is sent to the server doc.value = 'Draft content...' console.log(doc.isDirty.value) // true // Push to server when the user clicks Save doc.sync() ``` ## Examples ### Counter A simple counter that syncs across all clients: ```vue [Counter.vue] ``` ### Live Search Input Sync a search query with debouncing to avoid flooding the server: ```vue [LiveSearch.vue] ``` ### Collaborative Document Editor Let multiple users edit a document, but only push changes to the server when they explicitly save: ```vue [DocEditor.vue] ``` ### Shared Form A form where all fields sync in real-time: ```vue [SharedForm.vue] ``` ### Online Users List Track online users across sessions: ```vue [OnlineUsers.vue] ``` ### With Loading State Show a loading indicator while fetching initial state: ```vue [WithLoading.vue] ``` ### Disable Optimistic Updates For critical data where you want to wait for server confirmation before showing changes: ```vue [CriticalData.vue] ``` ## Conflict Resolution When multiple clients write to the same key at the same time, the **last write wins**. Whichever update the server stores last becomes the authoritative value, and it's broadcast to all subscribers. The behavior per strategy: | Strategy | Local update | On server error | On incoming update | | ----------- | ----------------------- | ----------------------------- | ---------------------------------------- | | `immediate` | Optimistic (if enabled) | Reverts to previous value | Overwrites local value, clears `isDirty` | | `debounced` | Optimistic immediately | Reverts to pre-debounce value | Overwrites local value, clears `isDirty` | | `manual` | Always immediate | `isDirty` remains `true` | Overwrites local value, clears `isDirty` | For `manual` mode, an incoming update from another client will overwrite any unsaved local changes. If you need to detect this, watch `isDirty` alongside the value: ```ts const doc = useRealtimeState('document', '', { sync: 'manual' }) watch(() => doc.value, () => { // isDirty will be false if this change came from the server if (!doc.isDirty.value) { console.log('Document was updated by another client') } }) ``` ## State Persistence Across Reconnections If a client disconnects while a sync is pending (e.g. during a network drop), the value is queued locally and automatically flushed to the server once the connection is restored. This applies to all three strategies. On reconnect, the composable also re-fetches the latest server value before flushing the queue, so stale local changes are applied on top of the most recent server state. ## How It Works 1. **Initial load**: on mount, the composable fetches the current value from the server. While waiting, `loading` is `true`. 2. **Subscription**: after the initial fetch, the client subscribes to updates for the given key. 3. **Updates**: when you assign a new value: - `immediate`: the change is sent to the server right away; with optimistic updates, the UI changes before confirmation. - `debounced`: the change updates the local ref immediately but the server call is delayed until the user stops changing the value. - `manual`: only the local ref is updated; nothing is sent until you call `sync()`. 4. **Broadcast**: when the server receives a new value it broadcasts `storage:updated` to all other subscribed clients. 5. **Cleanup**: on unmount, the subscription is removed and any pending debounce timer is cancelled. # useRealtimeEvents Publish and subscribe to events across clients in real-time. Perfect for notifications, chat messages, live updates, or any ephemeral communication that doesn't need to be persisted. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeEvents>( options?: UseRealtimeEventsOptions ): UseRealtimeEventsReturn ``` ## Options ```ts interface UseRealtimeEventsOptions { /** * Timeout for publish acknowledgments in milliseconds * @default 5000 */ publishTimeout?: number /** * Middleware functions applied to every incoming event before subscribers are called. * Each middleware receives the mutable event object and a `next` function. * Mutate `event.data` to transform the payload; omit calling `next()` to block the event. */ middleware?: EventMiddleware[] } type EventMiddleware = ( event: { channel: string; data: unknown }, next: () => void ) => void ``` ## Return Value ```ts interface UseRealtimeEventsReturn> { subscribe: ( channel: K, callback: (data: K extends keyof TEventMap ? TEventMap[K] : unknown, actualChannel?: string) => void ) => () => void publish: ( channel: K, data: TEventMap[K], options?: UseRealtimeEventsPublishOptions ) => Promise unsubscribe: (channel: string) => void } ``` ## Methods ### subscribe() Subscribe to events on a channel. Supports exact channel names, namespace wildcards (`chat:*`), and the global wildcard (`*`). When using a wildcard pattern, the callback receives the actual matched channel name as a second argument. ```ts subscribe( channel: K, callback: (data: unknown, actualChannel?: string) => void ): () => void ``` **Parameters:** | Parameter | Type | Description | | ---------- | -------------------------------- | ----------------------------------------- | | `channel` | `string` | Channel name, `namespace:*`, or `*` | | `callback` | `(data, actualChannel?) => void` | Function called when an event is received | **Returns:** An unsubscribe function ```ts const { subscribe } = useRealtimeEvents() // Basic subscription subscribe('chat', (message) => { console.log('New message:', message) }) // With TypeScript interface ChatMessage { user: string text: string timestamp: number } subscribe('chat', (message) => { console.log(`${message.user}: ${message.text}`) }) // Store unsubscribe function const unsubscribe = subscribe('channel', callback) // Later, unsubscribe unsubscribe() ``` ### publish() Publish an event to a channel. ```ts publish( channel: string, data: T, options?: UseRealtimeEventsPublishOptions ): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | --------------------------------- | ------------------------------ | | `channel` | `string` | The channel name to publish to | | `data` | `T` | The event data to send | | `options` | `UseRealtimeEventsPublishOptions` | Optional settings | **Returns:** A Promise that resolves when the server acknowledges the event ```ts const { publish } = useRealtimeEvents() // Basic publish await publish('notifications', { message: 'Hello!' }) // With error handling try { await publish('chat', { user: 'Alice', text: 'Hello everyone!', timestamp: Date.now(), }) } catch (error) { console.error('Failed to send message:', error) } ``` ### unsubscribe() Unsubscribe from all callbacks on a channel. ```ts unsubscribe(channel: string): void ``` ```ts const { subscribe, unsubscribe } = useRealtimeEvents() subscribe('channel', callback1) subscribe('channel', callback2) // Remove all subscriptions for this channel unsubscribe('channel') ``` ## Wildcard Subscriptions Subscribe to multiple channels at once using wildcard patterns. ### Namespace wildcard (`namespace:*`) Matches any channel that starts with the given prefix: ```ts const { subscribe, publish } = useRealtimeEvents() // Receives chat:message, chat:typing, chat:leave: any channel starting with 'chat:' subscribe('chat:*', (data, channel) => { console.log(`Event on ${channel}:`, data) }) await publish('chat:message', { text: 'Hello' }) // triggers the wildcard subscriber await publish('chat:typing', { userId: '1' }) // triggers the wildcard subscriber await publish('notifications', { msg: 'Alert' }) // does NOT trigger ``` ### Global wildcard (`*`) Receives every event published on any channel: ```ts subscribe('*', (data, channel) => { console.log(`[${channel}]`, data) }) ``` ### Exact and wildcard together Exact and wildcard subscribers for the same channel each receive the event once: ```ts subscribe('chat:message', (data) => { /* exact */ }) subscribe('chat:*', (data, channel) => { /* wildcard */ }) await publish('chat:message', { text: 'Hi' }, { includeSelf: true }) // Both callbacks fire exactly once ``` ::callout{icon="i-lucide-info"} Wildcard matching is based on channel prefixes. `chat:*` matches `chat:message`, `chat:typing`, and `chat:room:message`: any channel whose name starts with `chat:`. :: ## Event Middleware Middleware runs before any subscriber callbacks and receives a mutable `event` object. Call `next()` to continue the pipeline; omit it to block the event entirely. ```ts const { subscribe, publish } = useRealtimeEvents({ middleware: [ // Validation: block events that fail a check (event, next) => { if (isValid(event.data)) next() }, // Transformation: mutate event.data before subscribers see it (event, next) => { event.data = { ...event.data, receivedAt: Date.now() } next() }, ], }) ``` Middleware is applied to every incoming event for the composable instance that declares it. ## Type-Safe Events Pass an event map as a generic type parameter to get compile-time type checking on channel names and their payloads: ```ts interface AppEvents { 'chat:message': { text: string; userId: string } 'chat:typing': { userId: string } 'user:join': { userId: string; name: string } } const { publish, subscribe } = useRealtimeEvents() // publish: channel and data are both fully typed publish('chat:message', { text: 'Hello', userId: '1' }) // ✓ publish('chat:message', { text: 'Hello' }) // ✗ missing userId publish('unknown:channel', { text: 'Hello' }) // ✗ not in AppEvents // subscribe: data parameter is automatically typed subscribe('chat:message', (data) => { console.log(data.text, data.userId) // typed as { text: string; userId: string } }) ``` ## Publish Options ```ts interface UseRealtimeEventsPublishOptions { /** * Whether to also receive this event back on your own subscriptions * @default false */ includeSelf?: boolean } ``` ### includeSelf By default, when you publish an event, you don't receive it back on your own subscriptions. Set `includeSelf: true` on `publish` to receive it: ```ts const { subscribe, publish } = useRealtimeEvents() subscribe('chat', (msg) => console.log(msg)) // Won't receive own events (default) publish('chat', { text: 'Hello' }) // callback NOT triggered // Will receive own events publish('chat', { text: 'Hello' }, { includeSelf: true }) // callback IS triggered ``` ::callout{icon="i-lucide-info"} `includeSelf` is a `publish`-time decision. It applies to every subscriber on this client, not a per-subscription setting. :: ## Examples ### Chat Messages Real-time chat with message history: ```vue [Chat.vue] ``` ### Toast Notifications Broadcast notifications to all clients: ```vue [Notifications.vue] ``` ### Live Cursors Show other users' cursor positions: ```vue [LiveCursors.vue] ``` ### Typing Indicators Show when other users are typing: ```vue [TypingIndicator.vue] ``` ## Differences from useRealtimeState | Feature | useRealtimeState | useRealtimeEvents | | ----------------- | ----------------------------- | ----------------------- | | **Persistence** | State persisted on server | Events are ephemeral | | **Initial Value** | Loaded from server on mount | No initial value | | **Use Case** | Shared data (counters, lists) | Notifications, messages | | **API Style** | Reactive ref | Pub/sub callbacks | Use `useRealtimeState` when you need persistent, shared state. Use `useRealtimeEvents` when you want to broadcast ephemeral messages or notifications. # useRealtimeConnection Monitor and control the WebSocket connection status. Use this composable to show connection indicators, handle reconnection logic, or manually control the connection. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeConnection( options?: UseRealtimeConnectionOptions ): UseRealtimeConnectionReturn ``` ## Options ```ts interface UseRealtimeConnectionOptions { onConnected?: () => void onDisconnected?: (reason: string) => void onReconnecting?: (attempt: number) => void onReconnected?: (attempt: number) => void onReconnectFailed?: () => void onError?: (error: Error) => void } ``` ### Event Callbacks | Callback | Description | | ------------------- | --------------------------------------------------------- | | `onConnected` | Called when connection is established | | `onDisconnected` | Called when disconnected, with disconnect reason | | `onReconnecting` | Called on each reconnection attempt, with attempt number | | `onReconnected` | Called after successful reconnection, with total attempts | | `onReconnectFailed` | Called when all reconnection attempts have failed | | `onError` | Called on connection errors | ## Return Value ```ts interface UseRealtimeConnectionReturn { // Reactive state connected: Readonly> status: Readonly> attempt: Readonly> // Methods connect: () => void disconnect: () => void // Raw socket socket: Socket } type ConnectionStatus = 'connected' | 'disconnected' | 'connecting' | 'reconnecting' ``` ### connected A readonly boolean ref indicating if the socket is currently connected: ```ts const { connected } = useRealtimeConnection() watchEffect(() => { if (connected.value) { console.log('Online') } else { console.log('Offline') } }) ``` ### status A readonly ref with the current connection status: | Status | Description | | -------------- | ---------------------------------------- | | `connected` | Successfully connected to the server | | `disconnected` | Not connected to the server | | `connecting` | Initial connection in progress | | `reconnecting` | Attempting to reconnect after disconnect | ```ts const { status } = useRealtimeConnection() const statusMessage = computed(() => { switch (status.value) { case 'connected': return 'Online' case 'disconnected': return 'Offline' case 'connecting': return 'Connecting...' case 'reconnecting': return 'Reconnecting...' } }) ``` ### attempt A readonly ref with the current reconnection attempt number. `undefined` when not reconnecting: ```ts const { status, attempt } = useRealtimeConnection() // Only defined during reconnection if (status.value === 'reconnecting') { console.log(`Reconnection attempt ${attempt.value}`) } ``` ### connect() Manually initiate a connection: ```ts const { connect, disconnect } = useRealtimeConnection() // Disconnect disconnect() // Later, reconnect connect() ``` ### disconnect() Manually disconnect from the server: ```ts const { disconnect } = useRealtimeConnection() function goOffline() { disconnect() } ``` ### socket Access the raw Socket.IO socket instance for advanced usage: ```ts const { socket } = useRealtimeConnection() // Listen to custom events socket.on('custom-event', (data) => { console.log('Custom event:', data) }) // Emit custom events socket.emit('custom-event', { foo: 'bar' }) ``` ::callout{color="warning" icon="i-lucide-triangle-alert"} Direct socket access is an escape hatch. Prefer using `useRealtimeState` and `useRealtimeEvents` for most use cases. :: ## Examples ### Connection Status Badge Show a visual indicator of the connection status: ```vue [ConnectionBadge.vue] ``` ### Connection Events Logging Log all connection events for debugging: ```vue [ConnectionLogger.vue] ``` ### Offline Banner Show a banner when disconnected: ```vue [OfflineBanner.vue] ``` ### Manual Connection Control Let users manually control their connection: ```vue [ConnectionControl.vue] ``` ### Disable Features When Offline Conditionally disable features based on connection status: ```vue [OnlineOnly.vue] ``` ## Disconnect Reasons The `onDisconnected` callback receives a reason string. Common reasons include: | Reason | Description | | ---------------------- | ----------------------------------------------------- | | `io server disconnect` | Server forcefully disconnected the client | | `io client disconnect` | Client called `socket.disconnect()` | | `ping timeout` | Server didn't respond to ping within timeout | | `transport close` | Connection was closed (network issue, server restart) | | `transport error` | Connection encountered an error | ```ts useRealtimeConnection({ onDisconnected: (reason) => { if (reason === 'io server disconnect') { // Server kicked us out, may need to re-authenticate console.log('Server disconnected us') } else if (reason === 'io client disconnect') { // We disconnected intentionally console.log('We disconnected') } else { // Network issue, will auto-reconnect console.log('Connection lost, reconnecting...') } }, }) ``` # useRealtimePresence Track which clients are currently present in a room, with optional info about each one (a name, avatar, cursor position). Useful for "who's viewing this page" indicators, avatar stacks, and online lists. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimePresence( room: string, options?: UseRealtimePresenceOptions ): UseRealtimePresenceReturn ``` ## Parameters ### room - **Type:** `string` - **Required:** Yes An opaque group tag. All clients calling `useRealtimePresence` with the same `room` string see each other. It's just a string key, not tied to routes or URLs, so you can scope it however makes sense (a document id, a page path, a chat channel). ### options - **Type:** `UseRealtimePresenceOptions` - **Required:** No ```ts interface UseRealtimePresenceOptions { /** * Opaque data shown to other room members (e.g. `{ name, avatarUrl }`). Given up front, this * client auto-joins the room on setup; omit it to only observe who else is present. */ info?: TInfo } ``` Passing `info` joins the room immediately as a member. Omitting it lets you observe who's present without appearing in `members` yourself, useful for a spectator view. ## Return Value ```ts interface UseRealtimePresenceReturn { members: Readonly>> join: () => Promise leave: () => Promise } ``` ### members A readonly ref keyed by connection id, with the `info` each member joined with: ```ts const { members } = useRealtimePresence('document:123') watchEffect(() => { console.log(`${Object.keys(members.value).length} people here`) }) ``` ### join() Joins the room using the `info` passed to the composable. Called automatically if `info` was provided; call it manually if you joined without `info` and want to become a member later. It resolves to `true` when the server accepted the join and `false` when it was denied, for example by a `canJoinRoom` hook: ```ts const { join } = useRealtimePresence('document:123') async function startEditing() { if (!await join()) console.log('Not allowed to join') } ``` The server decides what other members see. With `auth: 'required'`, `info` is `null` unless a `nuxt-realtime:publicInfo` hook sets it, because the value you pass is untrusted. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app#presence-and-lock-info). ### leave() Leaves the room. Also called automatically on unmount: ```ts const { leave } = useRealtimePresence('document:123') function stopEditing() { leave() } ``` ## Examples ### Who's Viewing This Page Show an avatar stack of everyone currently viewing: ```vue [ViewerAvatars.vue] ``` ### Read-Only Viewer Count Observe the room without joining it, useful for a dashboard that shows activity without appearing as a "viewer" itself: ```vue [ViewerCount.vue] ``` # useRealtimeLock Claim exclusive ownership of a key across all connected clients. Use this to prevent two users from editing the same record at once, dragging the same card, or otherwise stepping on each other. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeLock( key: string, options?: UseRealtimeLockOptions ): UseRealtimeLockReturn ``` ## Parameters ### key - **Type:** `string` - **Required:** Yes A unique identifier for the lock. All clients using the same key contend for the same lock. ### options - **Type:** `UseRealtimeLockOptions` - **Required:** No ```ts interface UseRealtimeLockOptions { /** Info about this client to show others while it holds the lock (e.g. `{ name, avatarUrl }`) */ ownerInfo?: TOwnerInfo /** Opaque group tag for bulk presence via useRealtimeLockRoom. Not a route/URL concept. */ room?: string /** * Auto-release after this many ms of being held, regardless of activity. * Omitted = the module-level `lock.defaultTtl` (if any), 0 = never expires. */ ttl?: number /** Called whenever the lock becomes free */ onReleased?: (payload: { changed: boolean }) => void } ``` ## Return Value ```ts interface UseRealtimeLockReturn { claim: () => Promise release: (options?: { changed?: boolean, meta?: unknown }) => Promise forceRelease: () => Promise ownedByMe: Readonly> locked: Readonly> ownerInfo: Readonly> } ``` ### claim() Attempts to claim the lock. Succeeds if it's currently free or already owned by this client: ```ts const { claim } = useRealtimeLock('document:123', { ownerInfo: { name: 'Alice' }, }) const success = await claim() if (!success) { console.log('Someone else already holds this lock') } ``` ### release() Releases the lock. Resolves once the server has acknowledged; a no-op if this client doesn't own it: ```ts const { claim, release } = useRealtimeLock('document:123') await claim() // ... editing happens ... await release() ``` Pass `changed: true` when the release follows an actual edit, so other clients' `onReleased` can tell that apart from someone abandoning without changing anything. `meta` is relayed verbatim to other clients, useful for passing a diff or a reason: ```ts await release({ changed: true, meta: { field: 'title' } }) ``` ### forceRelease() Forcibly releases the lock regardless of who holds it. Denied by default: it only succeeds if the server has a `nuxt-realtime:canForceRelease` hook registered that sets `ctx.allow = true`. ```ts const { forceRelease } = useRealtimeLock('document:123') async function unlockAsAdmin() { const success = await forceRelease() if (!success) console.log('Not allowed to force-release') } ``` Register the hook on the server: ```ts [server/plugins/realtime-force-release.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canForceRelease', (ctx) => { ctx.allow = isAdmin(ctx.connectionId) }) }) ``` ### ownedByMe Whether this client currently owns the lock: ```ts const { ownedByMe } = useRealtimeLock('document:123') watchEffect(() => { if (ownedByMe.value) console.log('I hold the lock') }) ``` ### locked Whether anyone (not necessarily this client) currently owns the lock: ```ts const { locked, ownedByMe } = useRealtimeLock('document:123') const canEdit = computed(() => !locked.value || ownedByMe.value) ``` ### ownerInfo Info about the current holder, passed to their `claim()`'s `ownerInfo` option, or `null` if unlocked or unknown: ```vue ``` ## TTL: Auto-Release After a Timeout By default a lock stays held until it's explicitly released, or the owning connection disconnects. Set `ttl` to also release it automatically after a fixed duration, regardless of activity, useful as a safety net against a client that crashes without releasing cleanly: ```ts const { claim } = useRealtimeLock('document:123', { ttl: 60_000, // auto-release after 1 minute }) ``` Set a module-wide default in `nuxt.config.ts` instead of repeating `ttl` everywhere: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { lock: { defaultTtl: 60_000, }, }, }) ``` ## Examples ### Exclusive Form Editing Only let one user edit a record at a time: ```vue [RecordEditor.vue] ``` ### Kanban Card Drag Lock Prevent two users from dragging the same card at once: ```vue [KanbanCard.vue] ``` ::callout{icon="i-lucide-info"} See [`useRealtimeLockRoom`](https://nuxtrealtime.com/composables/userealtimelockroom) for a bulk view of every locked card on the board at once, so you don't need to subscribe to each card's lock individually. :: ### Notify Others When a Lock Is Released React when a lock someone else held becomes free, distinguishing a real edit from an abandoned session: ```ts const documentData = useRealtimeState('document:123', null) const { claim } = useRealtimeLock('document:123', { onReleased: ({ changed }) => { if (changed) { documentData.refresh() } }, }) ``` # useRealtimeLockRoom Get a read-only overview of every lock tagged with a given `room`, without subscribing to each key individually. Pairs with [`useRealtimeLock`](https://nuxtrealtime.com/composables/userealtimelock)'s `room` option: any lock claimed with the same `room` string shows up here. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeLockRoom(room: string): UseRealtimeLockRoomReturn ``` ## Parameters ### room - **Type:** `string` - **Required:** Yes The same opaque group tag passed as the `room` option to `useRealtimeLock`. All locks claimed with that tag appear in this composable's `locks`. ## Return Value ```ts interface UseRealtimeLockRoomReturn { locks: Readonly> } type LockRoomSnapshot = Record ``` ### locks Current `{ [key]: { owner, ownerInfo } }` for every lock tagged with this room. A key with no entry is unlocked: ```ts const { locks } = useRealtimeLockRoom('board:main') const lockedCount = computed(() => Object.keys(locks.value).length) ``` ## Examples ### Locked Cards Overview on a Kanban Board Show which cards are currently being edited across the whole board, without a per-card subscription: ```vue [KanbanBoard.vue] ``` ### Spreadsheet Cell Locks Highlight cells currently locked by other users while editing a shared sheet: ```vue [Spreadsheet.vue] ``` # useRealtimeRoom An explicit room concept that scopes [`useRealtimeState`](https://nuxtrealtime.com/composables/userealtimestate), [`useRealtimeEvents`](https://nuxtrealtime.com/composables/userealtimeevents), [`useRealtimePresence`](https://nuxtrealtime.com/composables/userealtimepresence), and [`useRealtimeLock`](https://nuxtrealtime.com/composables/userealtimelock) together under one id, with server-side lifecycle hooks and a single auth checkpoint instead of gating every handler individually. It's a convenience layer, not a requirement. `useRealtimeLock(key, { room })` and `useRealtimePresence(room)` keep working standalone without ever calling `useRealtimeRoom`; they pass through the same server-side membership path implicitly. ## Usage ```vue ``` ## Type Signature ```ts function useRealtimeRoom(roomId: string): UseRealtimeRoomReturn ``` ## Parameters ### roomId - **Type:** `string` - **Required:** Yes A unique identifier for the room. Calling `useRealtimeRoom` joins it immediately. ## Return Value ```ts interface UseRealtimeRoomReturn { joined: Readonly> join: () => Promise leave: () => Promise presence: (options?: UseRealtimePresenceOptions) => UseRealtimePresenceReturn lock: (key: string, options?: Omit, 'room'>) => UseRealtimeLockReturn locks: () => UseRealtimeLockRoomReturn state: (key: string, defaultValue?: T, options?: useRealtimeStateOptions) => UseRealtimeStateReturn events: >(options?: UseRealtimeEventsOptions) => UseRealtimeEventsReturn } ``` ### joined Whether this client is currently a member of the room, reflecting the last join/leave acknowledgment: ```ts const room = useRealtimeRoom('document:123') watchEffect(() => { if (!room.joined.value) console.log('Not in the room') }) ``` ### join() / leave() `useRealtimeRoom` joins automatically on setup and leaves on unmount. Call these directly for manual control: ```ts const room = useRealtimeRoom('document:123') async function switchDocument() { await room.leave() // ... navigate elsewhere ... } ``` `join()` resolves to whether it succeeded. It's gated server-side by the `nuxt-realtime:canJoinRoom` hook (allowed by default, denied with `auth: 'required'` unless a hook allows it). ### presence() Presence scoped to this room, equivalent to `useRealtimePresence(roomId, options)`: ```ts const room = useRealtimeRoom('document:123') const { members } = room.presence({ info: { name: 'Alice' } }) ``` ### lock() A lock scoped to this room, equivalent to `useRealtimeLock(key, { ...options, room: roomId })`: ```ts const room = useRealtimeRoom('document:123') const { claim, release, ownedByMe } = room.lock('editing') ``` ### locks() Read-only, bulk view of every lock claimed via `room.lock()` in this room, equivalent to `useRealtimeLockRoom(roomId)`. Use this for an overview across many keys; use `lock(key)` to claim or release one specific key: ```ts const room = useRealtimeRoom('board:main') const { locks } = room.locks() ``` ### state() State scoped to this room. A thin client-side convenience that namespaces `key` under the room id and delegates to `useRealtimeState`; it adds no new server protocol: ```ts const room = useRealtimeRoom('document:123') const title = room.state('title', 'Untitled') ``` ### events() Event pub/sub scoped to this room. Namespaces the channel under the room id and delegates to `useRealtimeEvents`: ```ts const room = useRealtimeRoom('document:123') const { subscribe, publish } = room.events() subscribe('comment-added', (comment) => { console.log('New comment:', comment) }) publish('comment-added', { text: 'Nice work!' }) ``` ## Server Hooks `useRealtimeRoom` fires three server-side hooks around joining and leaving. Register them in a Nitro plugin. ### Gating who can join `nuxt-realtime:canJoinRoom` is the single checkpoint for per-room auth. It runs on every explicit join, so a client that reconnects and joins again is checked again. The default is allow, or deny when `auth` is `'required'`. Set `ctx.allow = true` to allow, or `ctx.deny(reason)` to deny: ```ts [server/plugins/realtime-room-auth.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canJoinRoom', async (ctx) => { ctx.allow = await userCanAccessRoom(ctx.user, ctx.roomId) }) }) ``` Several hooks can be registered. Each one votes, and any deny wins. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app#how-hooks-combine). ### Room created / emptied `nuxt-realtime:roomCreated` fires once when a room's membership goes from 0 to 1, the natural place for provisioning logic: ```ts [server/plugins/realtime-room-lifecycle.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:roomCreated', async ({ roomId }) => { await db.rooms.upsert({ id: roomId, createdAt: new Date() }) }) nitroApp.hooks.hook('nuxt-realtime:roomEmpty', async ({ roomId }) => { await db.rooms.archive(roomId) }) }) ``` `nuxt-realtime:roomEmpty` fires once when membership goes from 1 to 0, either an explicit leave that empties the room or (after every member's disconnect grace period lapses without a reconnect) the connection registry's sweep. ## Examples ### Collaborative Document Page Combine presence, a title lock, and shared state on a single document page: ```vue [DocumentPage.vue] ``` # Architecture Nuxt Realtime connects four systems together: 1. **Nitro**: Nuxt's server engine, handling all HTTP and WebSocket traffic 2. **h3 / crossws**: the lower-level frameworks Nitro builds on (h3 for HTTP, crossws for WebSockets) 3. **Engine.IO**: Socket.IO's transport layer, which works directly with raw Node.js primitives 4. **Socket.IO**: the application-level library that gives us rooms, events, and acknowledgements The tricky part is that Nitro wraps Node.js primitives in its own abstractions, but Engine.IO and Socket.IO expect raw Node.js objects. The server plugin bridges that gap. For how cross-server sync works on top of this, see [Notification Layer](https://nuxtrealtime.com/technical/pubsub) and [Multi-Server Sync](https://nuxtrealtime.com/technical/cross-server-sync). ## Connection flow ::mermaid --- :config: config code: graph%20TD%0A%20%20%20%20Client%5B%22Browser%22%5D%0A%20%20%20%20Client%20--%20%22%2Fsocket.io%2F%22%20--%3E%20Nitro%0A%0A%20%20%20%20subgraph%20Nitro%5B%22Nitro%22%5D%0A%20%20%20%20%20%20%20%20H3%5B%22h3%20-%20HTTP%22%5D%0A%20%20%20%20%20%20%20%20CrossWS%5B%22crossws%20-%20WebSocket%22%5D%0A%20%20%20%20end%0A%0A%20%20%20%20subgraph%20Bridge%5B%22Bridge%20Layer%22%5D%0A%20%20%20%20%20%20%20%20Unwrap%5B%22Unwraps%20to%20raw%20Node.js%20objects%22%5D%0A%20%20%20%20end%0A%0A%20%20%20%20H3%20--%3E%20Unwrap%0A%20%20%20%20CrossWS%20--%3E%20Unwrap%0A%0A%20%20%20%20Unwrap%20--%3E%20EngineIO%5B%22Engine.IO%20-%20Transport%22%5D%0A%20%20%20%20EngineIO%20--%3E%20SocketIO%5B%22Socket.IO%20-%20Application%22%5D%0A%20%20%20%20SocketIO%20--%3E%20Storage%5B%22Storage%20sync%22%5D%0A%20%20%20%20SocketIO%20--%3E%20Events%5B%22Pub%2Fsub%20events%22%5D --- :: ## The bridge layer Everything goes through a route handler registered at `/socket.io/`. It's an h3 event handler with two hooks: one for HTTP, one for WebSocket: ```ts nitroApp.router.use('/socket.io/', defineEventHandler({ handler(event) { // HTTP requests (long-polling transport) // Unwrap h3's H3Event to get the raw Node.js req/res engine.handleRequest(event.node.req, event.node.res) event._handled = true }, websocket: { async upgrade(request) { // Runs before the 101 response: origin check and authenticate hook. // Returning a Response (401 or 403) ends the upgrade. }, open(peer) { // WebSocket connections // Unwrap crossws's Peer to get the raw Node.js request and socket engine.prepare(peer._internal.nodeReq) engine.onWebSocket( peer._internal.nodeReq, peer._internal.nodeReq.socket, peer.websocket ) }, }, })) ``` Each layer produces different objects, and Engine.IO needs the raw Node.js ones: | Layer | Provides | | ------------- | ---------------------------------------------------------------------------------------------------------- | | **Nitro/h3** | `H3Event` with `event.node.req` / `event.node.res` | | **crossws** | `Peer` with `peer._internal.nodeReq` / `peer.websocket` | | **Engine.IO** | Expects raw `IncomingMessage` + `ServerResponse` (HTTP) or `IncomingMessage` + `Socket` + `WebSocket` (WS) | The bridge just extracts the right objects and passes them through. ### HTTP vs WebSocket transports Socket.IO supports two transports: - **HTTP long-polling**: used as a fallback or during the initial handshake. Goes through h3's `handler()`. - **WebSocket**: the primary transport. Goes through crossws's `websocket.upgrade()` hook, then `websocket.open()`. Both transports run the origin check and the `nuxt-realtime:authenticate` hook before the connection opens. Polling does it in Engine.IO's `allowRequest`, WebSocket in `upgrade`, so a refused client gets a `403` or `401` and never an open socket. With `auth: 'required'`, a connection that no hook identified is refused the same way. See [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app). Engine.IO upgrades from long-polling to WebSocket automatically when possible. ## Socket.IO and Engine.IO binding The two are wired together with a single call: ```ts const engine = new Engine() const io = new Server() io.bind(engine) ``` Engine.IO handles the raw connection; Socket.IO handles the event API on top. ## Data flow example What happens when a client calls `useRealtimeState('counter', 0)` and updates the value: 1. The client emits a `storage:set` event with `{ key: 'counter', value: 1 }` 2. The message travels over the WebSocket to Nitro 3. crossws passes it to the bridge, which hands it to Engine.IO 4. Engine.IO passes it up to Socket.IO 5. The `storage:set` handler stores the value via Nitro's storage and broadcasts `storage:updated` to the `key:counter` room. If a key is removed elsewhere in the server, the watch callback emits `storage:updated` with `value: null` to the same room. 6. Other clients in that room receive the update, reset on removal, and their local state refreshes # Notification Layer Cross-server sync is split into two separate concerns: storing data and notifying other servers that something changed. This page covers the notification side. ## Two layers, two responsibilities ::mermaid --- :config: config code: flowchart%20TD%0A%20%20%20%20A%5B%22**Server%20plugin**%5CnHandles%20Socket.IO%20events%2C%20storage%20CRUD%2C%20event%20relay%22%5D%0A%20%20%20%20A%20--%3E%20B%5B%22**Storage%20layer**%5Cnunstorage%20%2B%20Redis%5CnData%20persistence%22%5D%0A%20%20%20%20A%20--%3E%20C%5B%22**Notification%20layer**%5CnRealtimePubSub%5CnCross-server%20messaging%20only%22%5D --- :: The **storage layer** (backed by [unstorage](https://unstorage.unjs.io/){rel=""nofollow""}) owns all data. Reads and writes go through here. The **notification layer** (`RealtimePubSub`) owns no data at all. Its only job is to tell other server instances that something happened. It forwards the payload but never persists it. Keeping them separate means you can reason about each independently. A storage problem won't affect the messaging path, and the other way around. ## RealtimePubSub `RealtimePubSub` is a class exported from `nuxt-realtime/drivers/redis`. It holds exactly two Redis connections for the lifetime of the server process: | Connection | Direction | Purpose | | ---------- | --------- | ------------------------------------------------------------- | | `pub` | outbound | Publishes messages to Redis channels | | `sub` | inbound | Subscribes to Redis channels and dispatches incoming messages | Multiple features (storage sync, event relay and the presence and lock relay) share these two connections. There are no extra connections per feature. ```ts const pubsub = new RealtimePubSub({ host: 'localhost', port: 6379 }) // Subscribe to a channel, returns an unsubscribe function const unsub = pubsub.subscribe('some-channel', (message) => { const payload = JSON.parse(message) // handle payload }) // Publish to a channel await pubsub.publish('some-channel', { hello: 'world' }) // Clean up both connections await pubsub.dispose() ``` For Redis Cluster, pass `cluster` instead of `host`/`port`/`url` as it takes priority over them: ```ts const pubsub = new RealtimePubSub({ cluster: [{ host: 'redis-1', port: 6379 }, { host: 'redis-2', port: 6379 }], }) ``` ## Channels Three Redis channels are used internally: | Channel | Used by | Payload | | ------------------------- | ----------------------- | ----------------------------------- | | `nuxt-realtime:watch` | Reactive storage driver | `{ event, key, origin }` | | `nuxt-realtime:events` | Event relay | `{ channel, data, origin }` | | `nuxt-realtime:broadcast` | Presence and lock relay | `{ rooms, event, payload, origin }` | All include an `origin` field with the `instanceId` of the server that sent the message. ## Deduplication via instanceId Each `RealtimePubSub` instance generates a UUID when it starts up. Every published message includes this as `origin`. When a message comes in over the subscriber connection, the server compares `origin` to its own `instanceId` and skips the message if they match. This stops the publishing server from reacting to its own broadcast: ```text Server A publishes -> Redis pub/sub -> Server A receives (origin matches, skip) -> Server B receives (origin differs, relay) -> Server C receives (origin differs, relay) ``` Without this, Server A would broadcast every change twice: once from the direct Socket.IO emit, and once from the pub/sub relay. ## Connection lifecycle `RealtimePubSub` starts up once per server process inside the Nitro plugin, before any Socket.IO connections come in. It gets passed to the storage driver so both features share the same instance. ::mermaid --- :config: config code: flowchart%20TD%0A%20%20%20%20A(%5BNitro%20plugin%20starts%5D)%20--%3E%20B%5Bnew%20RealtimePubSub%5D%0A%20%20%20%20B%20--%3E%20C%5BreactiveRedisDriver%5D%0A%20%20%20%20B%20--%3E%20D%5B%22pubsub.subscribe%5Cn(nuxt-realtime%3Aevents)%22%5D%0A%20%20%20%20C%20--%3E%20E%5Bregisters%20handler%20on%5Cnnuxt-realtime%3Awatch%5D%0A%20%20%20%20D%20--%3E%20F%5Bregisters%20handler%20on%5Cnnuxt-realtime%3Aevents%5D%0A%0A%20%20%20%20G(%5BNitro%20plugin%20shuts%20down%5D)%20--%3E%20H%5Bunwatch%5D%0A%20%20%20%20G%20--%3E%20I%5BunsubscribeEvents%5D%0A%20%20%20%20G%20--%3E%20J%5Bpubsub.dispose%5D%0A%20%20%20%20H%20--%3E%20K%5Bstorage%20driver%5Cnwatch%20removed%5D%0A%20%20%20%20I%20--%3E%20L%5Bevent%20relay%5Cnhandler%20removed%5D%0A%20%20%20%20J%20--%3E%20M%5Bpub%20%2B%20sub%5Cnconnections%20closed%5D --- :: ## No Redis configured When no Redis options are set (common in local development), `RealtimePubSub` is never created and the plugin runs in single-instance mode: - Storage updates only reach clients on the same server. - Events only reach subscribers on the same server. - Presence and lock changes only reach clients on the same server. # Multi-Server Sync By default, clients connected to the same server see each other's updates in real time. To make that work across multiple server instances, you need Redis. ## Configuration Add Redis connection details to your `nuxt.config.ts`: ```ts [nuxt.config.ts] export default defineNuxtConfig({ modules: ['nuxt-realtime'], nuxtRealtime: { redis: { host: 'localhost', port: 6379, // or: url: 'redis://localhost:6379' // password: '...', // db: 0, } } }) ``` That's all. Both of these work automatically once Redis is configured: - **Reactive state sync**: storage writes on any instance get broadcast to subscribers on all other instances - **Cross-server event relay**: events published via `useRealtimeEvents` on any instance reach subscribers everywhere - **Presence and lock relay**: presence and lock changes made through any instance reach clients on all others ## How state sync works ::mermaid --- :config: config code: sequenceDiagram%0A%20%20%20%20participant%20CA%20as%20Client%20A%0A%20%20%20%20participant%20S1%20as%20Server%201%0A%20%20%20%20participant%20R%20as%20Redis%0A%20%20%20%20participant%20S2%20as%20Server%202%0A%20%20%20%20participant%20CB%20as%20Client%20B%0A%0A%20%20%20%20CA-%3E%3ES1%3A%20storage%3Aset%0A%20%20%20%20S1-%3E%3ER%3A%20write%20value%0A%20%20%20%20S1-%3E%3ECA%3A%20storage%3Aupdated%20(local%20room)%0A%20%20%20%20S1-%3E%3ER%3A%20pub%20nuxt-realtime%3Awatch%0A%20%20%20%20R-%3E%3ES2%3A%20sub%20nuxt-realtime%3Awatch%0A%20%20%20%20S2-%3E%3ES2%3A%20watch%20callback%20fires%0A%20%20%20%20S2-%3E%3ECB%3A%20storage%3Aupdated%20(local%20room) --- :: 1. Client A emits `storage:set` or server-side code calls `storage.removeItem()`, which updates Redis and immediately emits `storage:updated` to the local room. 2. The change also publishes a notification to `nuxt-realtime:watch`. 3. Server 2 picks up the message, reads the current value from Redis, and broadcasts `storage:updated` to its local room. For removals, that value is `null`. 4. Client B receives the update or reset. Server 1 won't double-broadcast to its own clients because the `origin` field on the pub/sub message matches its own `instanceId`. See [Notification Layer](https://nuxtrealtime.com/technical/pubsub#deduplication-via-instanceid) for details. ## How event relay works ::mermaid --- :config: config code: sequenceDiagram%0A%20%20%20%20participant%20CA%20as%20Client%20A%0A%20%20%20%20participant%20S1%20as%20Server%201%0A%20%20%20%20participant%20R%20as%20Redis%0A%20%20%20%20participant%20S2%20as%20Server%202%0A%20%20%20%20participant%20CB%20as%20Client%20B%0A%0A%20%20%20%20CA-%3E%3ES1%3A%20event%3Apublish%0A%20%20%20%20S1-%3E%3ECA%3A%20event%3Areceived%20(local%20emit)%0A%20%20%20%20S1-%3E%3ER%3A%20pub%20nuxt-realtime%3Aevents%0A%20%20%20%20R-%3E%3ES2%3A%20sub%20nuxt-realtime%3Aevents%0A%20%20%20%20S2-%3E%3ES2%3A%20origin%20check%20passes%0A%20%20%20%20S2-%3E%3ECB%3A%20event%3Areceived%20(local%20room) --- :: 1. Client A emits `event:publish` to Server 1, which immediately broadcasts `event:received` to local subscribers. 2. Server 1 publishes the event payload (with its `instanceId` as `origin`) to `nuxt-realtime:events`. 3. Server 2 receives the message, sees the origin doesn't match its own ID, and relays it to its local Socket.IO room. 4. Client B receives the event. The `includeSelf` option controls whether the publishing socket sees its own event. That's handled entirely in the local broadcast step and has no effect on how the relay works. ## How presence and lock relay works Socket.IO room membership is per instance, so a `presence:changed` or `lock:changed` emitted on Server 1 would only reach Server 1's clients. Every such emit also publishes `{ rooms, event, payload, origin }` to `nuxt-realtime:broadcast`. Other instances re-emit it to their local rooms unless `origin` is their own `instanceId`. Presence, locks and room membership live in storage, so the instances must share it. Use the `redis` option. ## Dead instances Each instance writes a liveness timestamp (`_instance:{instanceId}`) on every sweep tick, and connection records remember which instance owns them. If an instance stays silent for longer than `instanceTimeoutMs` (default 30 seconds), the other instances mark its connections stale. After `lock.staleGraceMs` the usual sweep releases their locks, presence and room membership and broadcasts the change. A client that reconnects to another instance within about `instanceTimeoutMs` of the crash cannot reclaim its `connectionId` and gets a fresh one. ## Sticky sessions Engine.IO's polling transport keeps its session in memory on one instance. Use sticky sessions at your load balancer, or set `socketio.serverOptions.transports` to `['websocket']`. ## Redis connections Enabling Redis opens exactly two connections per server instance. Storage sync, event relay and the presence and lock relay share a single `RealtimePubSub` with one `pub` and one `sub` connection. | Connection | Role | | ---------- | ----------------------------------------------------------------------------------------- | | `pub` | Publishes storage and event notifications | | `sub` | Subscribes to `nuxt-realtime:watch`, `nuxt-realtime:events` and `nuxt-realtime:broadcast` | ## No Redis configured Without Redis the module falls back to single-server behavior. No client-side changes needed. Startup warnings will tell you sync is disabled. # Blocks Pre-built, copy-paste ready UI blocks for common realtime patterns. ::callout{color="warning" icon="i-lucide-construction"} **Coming Soon**: we're working on a collection of ready-to-use blocks for chat interfaces, presence indicators, live cursors, and more. :: ## What's Planned ::card-group :::card{icon="i-lucide-message-circle" title="Chat Interface"} A complete chat UI with message history, typing indicators, and user presence. ::: :::card{icon="i-lucide-users" title="Presence Avatars"} Show who's online with animated avatar stacks and status indicators. ::: :::card{icon="i-lucide-mouse-pointer-2" title="Live Cursors"} Display real-time cursor positions of other users on the page. ::: :::card{icon="i-lucide-bell" title="Notification Center"} A toast notification system for broadcasting alerts across clients. ::: :::card{icon="i-lucide-vote" title="Live Polls"} Real-time voting and polling with animated result bars. ::: :::card{icon="i-lucide-pen-tool" title="Collaborative Canvas"} A shared drawing canvas for real-time collaboration. ::: :: # Components Vue components designed specifically for realtime applications, built on top of the Nuxt Realtime composables. ::callout{color="warning" icon="i-lucide-construction"} **Coming Soon**: we're building a library of plug-and-play components for common realtime UI patterns. :: ## What's Planned ::card-group :::card{icon="i-lucide-wifi" title="ConnectionStatus"} A ready-to-use component that displays the current connection state with customizable styling. ::: :::card{icon="i-lucide-circle-user" title="PresenceAvatar"} Display user presence with avatars, online indicators, and idle states. ::: :::card{icon="i-lucide-keyboard" title="TypingIndicator"} Show animated typing indicators when other users are typing. ::: :::card{icon="i-lucide-mouse-pointer" title="LiveCursor"} Render other users' cursors with smooth animations and name labels. ::: :::card{icon="i-lucide-lock" title="RealtimeGuard"} Conditionally render content based on connection status. ::: :::card{icon="i-lucide-refresh-cw" title="SyncStatus"} Show sync state with pending changes indicator and conflict resolution. ::: :: # Nuxt Realtime 0.2 Nuxt Realtime 0.2 is out. Here's what's new since the last release. ## Rooms [`useRealtimeRoom`](https://nuxtrealtime.com/composables/userealtimeroom) ties state, events, presence, and locks together under one room id, with server-side lifecycle hooks and a single auth checkpoint instead of gating every handler individually. ```vue ``` See the [rooms docs](https://nuxtrealtime.com/composables/userealtimeroom) for details. ## Locking [`useRealtimeLock`](https://nuxtrealtime.com/composables/userealtimelock) claims exclusive ownership of a key across all connected clients, so only one user edits a record or drags a card at a time. ```vue ``` [`useRealtimeLockRoom`](https://nuxtrealtime.com/composables/userealtimelockroom) pairs with it for a bulk, read-only view of every lock tagged with a room, without subscribing to each key individually. :video{autoPlay="true" loop="true" muted="true" playsInline="true" src="https://nuxtrealtime.com/lock-demo.mp4"} See the [locking docs](https://nuxtrealtime.com/composables/userealtimelock) for details. ## Presence [`useRealtimePresence`](https://nuxtrealtime.com/composables/userealtimepresence) tracks which clients are currently present in a room, with optional info about each one (a name, avatar, cursor position). Useful for "who's viewing this page" indicators and avatar stacks. ```vue ``` :video{autoPlay="true" loop="true" muted="true" playsInline="true" src="https://nuxtrealtime.com/presence-demo.mp4"} See the [presence docs](https://nuxtrealtime.com/composables/userealtimepresence) for details. ## Realtime DevTools ![image](https://nuxtrealtime.com/realtime-devtools.png) A "Realtime" tab in [Nuxt DevTools](https://devtools.nuxt.com/){rel=""nofollow""} shows what's happening on the wire while you develop: active connections, subscribed channels and storage keys per socket, live storage values, and a scrolling event log. It's dev-only and never ships in production. See the [DevTools docs](https://nuxtrealtime.com/getting-started/devtools) for details. ## Connection authentication A new `nuxt-realtime:io` Nitro hook exposes the Socket.IO `Server` before any connections are accepted, so you can register `io.use()` middleware to authenticate or authorize clients — JWT, session cookies, or anything else. A matching `nuxt-realtime:auth` app hook lets the client attach a fresh token on every connection attempt, including reconnects. See the [Authentication docs](https://nuxtrealtime.com/getting-started/authentication) for details. ## Redis Cluster support The Redis driver now accepts a `cluster` option, so `reactiveRedisDriver()` can talk to a Redis Cluster instead of a single node: ```ts import { reactiveRedisDriver } from 'nuxt-realtime/drivers/redis' export default defineNuxtConfig({ nuxtRealtime: { storage: reactiveRedisDriver({ cluster: [{ host: 'redis-1', port: 6379 }, { host: 'redis-2', port: 6379 }], }), }, }) ``` See the [configuration docs](https://nuxtrealtime.com/getting-started/configuration) for details. ## Configurable Socket.IO path `socketio.path` lets you move the Socket.IO endpoint off the `/socket.io` default (useful behind a reverse proxy that already owns that path). The client and server now derive the same path from this single option. ## Fixes - Client-supplied storage keys can no longer read or write the internal `_lease:` namespace used for storage expiry. # Nuxt Realtime 0.2.1 Nuxt Realtime 0.2.1 is a security release. We recommend everyone upgrade. ## Origin check The realtime server now rejects cross-site WebSocket connections. Without `cors.origin`, only same-origin connections are accepted (`X-Forwarded-Host` is honored behind a proxy). With it set, only the listed origins get in. Clients that send no `Origin` header, such as server-side or native clients, are still accepted. ::callout{color="warning"} If your Nuxt app and realtime server run on different origins (for example a standalone server behind `socketio.serverUrl`), set `cors.origin` to your app's origin. The module logs a warning when `serverUrl` is set without it. :: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { socketio: { serverUrl: 'https://realtime.example.com', serverOptions: { cors: { origin: ['https://app.example.com'] } }, }, }, }) ``` See [origin check](https://nuxtrealtime.com/getting-started/configuration#origin-check). ## Reconnect identity A `connectionId` is visible to other clients, because it is the owner shown on locks and presence. It was never a credential, but it was treated like one. The server now issues a per-connection secret and only lets a client reclaim an id by presenting it, so nobody can take over another client's locks, presence or room membership. A client that loses its secret reconnects with a fresh identity. See [reconnect identity](https://nuxtrealtime.com/getting-started/authentication#reconnect-identity). ## Limits Each connection is now capped so a single client cannot exhaust server memory or storage. The defaults can be raised or lowered: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { limits: { maxKeyLength: 256, maxValueBytes: 262_144, maxKeysPerSocket: 1000, maxEventsPerSecond: 120, }, }, }) ``` ## Authorizing subscriptions and publishes Any client could subscribe to any event channel or lock. Two new Nitro hooks let you restrict that. Both allow by default, and a hook that throws denies: ```ts [server/plugins/realtime-auth.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canSubscribe', (ctx) => { if (ctx.kind === 'event') ctx.allow = !ctx.name.startsWith('admin:') && ctx.name !== '*' }) nitroApp.hooks.hook('nuxt-realtime:canPublish', (ctx) => { ctx.allow = ctx.channel.startsWith('chat:') }) }) ``` See [authorizing subscriptions and publishes](https://nuxtrealtime.com/getting-started/configuration#authorizing-reads-and-writes). ## Also in this release - Input validation on storage, lock, presence, room and event payloads. - Dependency updates for security fixes. - Node.js is locked to 24. The full list is in the [changelog](https://github.com/daanvangeloven/nuxt-realtime/blob/master/CHANGELOG.md){rel=""nofollow""}. # Nuxt Realtime 0.3 Nuxt Realtime 0.3 is out. 0.2.1 closed the most urgent gaps. This release lets you lock the realtime server down completely: every connection has a verified user, and every read, write and join goes through a hook you control. The full guide is [Securing your app](https://nuxtrealtime.com/getting-started/securing-your-app). ## Required authentication One option turns it on: ```ts [nuxt.config.ts] export default defineNuxtConfig({ nuxtRealtime: { auth: 'required', }, }) ``` Connections are authenticated in the new `nuxt-realtime:authenticate` Nitro hook. It runs before the transport opens, on the polling handshake and on the WebSocket upgrade, so a refused client gets a `401` or `403` and never an open socket. ```ts [server/plugins/realtime-authenticate.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:authenticate', async (ctx) => { const session = await getSession<{ user?: { id: string, name: string } }>(ctx.event, { password: process.env.SESSION_SECRET!, }) ctx.user = session.data.user }) }) ``` With `auth: 'required'`, a connection that no hook identified is refused, the gate hooks deny by default, and presence `info` and lock `ownerInfo` stay `null` until you set them on the server. Leave `auth` unset to keep accepting anonymous connections. For a cross-origin realtime server, where cookies don't reach it, send a token through `ctx.query` in the client `nuxt-realtime:auth` hook. See [token in the query](https://nuxtrealtime.com/getting-started/securing-your-app#token-in-the-query). ## Gate hooks for reads and writes `canJoinRoom`, `canSubscribe` and `canPublish` now have a sibling, `canWrite`, and `canSubscribe` also covers state reads (`storage:get`, `storage:subscribe`). `canForceRelease` controls who may take over a lock and always denies by default. Every gate gets `ctx.user` and `ctx.socket`, plus `ctx.deny(reason)`. The reason comes back to the client in the acknowledgement: ```ts [server/plugins/realtime-gates.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:canWrite', (ctx) => { const user = ctx.user as { id: string } if (ctx.key.startsWith(`user:${user.id}:`)) ctx.allow = true else ctx.deny('Not your key') }) }) ``` Hooks now vote. Any deny wins, then any allow, then the default, so a later hook can no longer undo an earlier deny. See [how hooks combine](https://nuxtrealtime.com/getting-started/securing-your-app#how-hooks-combine). ## Identity is owned by the server The verified user lives in `socket.data.user` and is set before your `io.use()` middleware runs. No client-supplied field can set the user, the connection owner or lock ownership. What other clients see in presence and lock info is decided by the new `nuxt-realtime:publicInfo` hook. The client's value only arrives as `ctx.clientInfo`: ```ts [server/plugins/realtime-public-info.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('nuxt-realtime:publicInfo', (ctx) => { const user = ctx.user as { name: string, avatarUrl: string } ctx.info = { name: user.name, avatarUrl: user.avatarUrl } }) }) ``` ## Extending the server Two new server auto-imports let you build on the same checks the built-in events use: - `guard(socket, { kind, name, data })` applies the rate limit, size limit and matching gate hook to a custom socket event. - `useRealtimeServer()` gives trusted server code `publish`, `getState` and `setState`, which reach clients on every instance. `nuxt-realtime:afterWrite` and `nuxt-realtime:afterPublish` fire after a successful write or publish, for audit logs, history and webhooks. See [extending the server](https://nuxtrealtime.com/getting-started/securing-your-app#extending-the-server). ## Multi-instance With Redis, presence and lock changes are now relayed to clients on every instance. Each instance also writes a liveness timestamp, and when one is silent for longer than the new `instanceTimeoutMs` (default 30 seconds) its locks, presence and room membership are released. A crashed instance no longer leaves them behind. ## Upgrading These changes apply even with `auth` unset: - A cross-origin WebSocket gets a `403` before the upgrade, instead of being opened and closed. - Gate hooks vote: `ctx.allow = true` no longer overrides another hook's deny, and `ctx.allow` starts as `undefined`. - `canJoinRoom` runs on every explicit join, so a revoked permission takes effect on reconnect. - `useRealtimePresence().join()` resolves to a `boolean`, and `members` values can be `null`. - An `authenticate` hook that rejects refuses the connection. - Calls dropped by the rate limit or from a rejected socket get a failed acknowledgement instead of hanging. The full list is in the [changelog](https://github.com/daanvangeloven/nuxt-realtime/blob/master/CHANGELOG.md){rel=""nofollow""}. # Welcome to the Nuxt Realtime blog We're using this space to share release notes and articles about building realtime experiences with Nuxt Realtime.