Getting Started

Securing your app

Require authentication, gate reads and writes with hooks, and extend the realtime server.
Read the 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.

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.

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.

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.

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:

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:

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)
  })
})
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. 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.

HookRuns onDefault
nuxt-realtime:canJoinRoomevery explicit join: room:join, presence:join, presence:subscribeRoom, lock:subscribeRoomallow, deny with auth: 'required'
nuxt-realtime:canSubscribeevent:subscribe, lock:subscribe, every lock:claim (with a room, canJoinRoom must allow too), and state reads: storage:get, storage:subscribeallow, deny with auth: 'required'
nuxt-realtime:canPublishevent:publishallow, deny with auth: 'required'
nuxt-realtime:canWritestorage:setallow, deny with auth: 'required'
nuxt-realtime:canForceReleaselock:forceReleasealways deny

Every gate context has user and socket next to its own fields:

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 }
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.

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 }
  })
})
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.

function guard(
  socket: Socket,
  options: { kind: 'write' | 'publish' | 'subscribe' | 'join', name: string, data?: unknown },
): Promise<{ allowed: boolean, reason?: string }>
kindGate hook it runs
writecanWrite (name is the key, data the value)
publishcanPublish (name is the channel, data the payload)
subscribecanSubscribe with kind: 'event'
joincanJoinRoom (name is the room id)

guard() does not check room capacity.

useRealtimeServer()

Trusted server-side access, with no gate hooks:

function useRealtimeServer(): {
  publish: (channel: string, data?: unknown) => Promise<void>
  getState: <T = unknown>(key: string) => Promise<T | null>
  setState: (key: string, value: StorageValue) => Promise<void>
}

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.

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():

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:

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:

src/module.ts
import { defineNuxtModule, createResolver, addServerPlugin } from '@nuxt/kit'

export interface ModuleOptions {
  maxLength?: number
}

export default defineNuxtModule<ModuleOptions>({
  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'))
  },
})
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 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.