Docs

WebSockets

app.ws(path, handler) registers a WebSocket route. It mirrors .get()/.post() - chainable, with per-connection state typed through a generic - and runs on every runtime Nifra serves: Bun, Deno, Node, and Cloudflare Workers.

The WebSocket runtime ships as an opt-in plugin, so apps that never use it don’t bundle it. Enable it with .use(websocket()) from @nifrajs/core/ws; app.ws() without it fails loud at registration with WS_RUNTIME_MISSING. It installs on that server instance only - the same .use() opt-in as mcp() and streaming().

TS
import { server } from "@nifrajs/core/server"
import { websocket } from "@nifrajs/core/ws" // .use(websocket()) enables app.ws()

const app = server()
  .use(websocket())
  .get("/", () => ({ ok: true }))
  .ws("/echo", {
    open: (ws) => ws.send("welcome"),
    message: (ws, data) => ws.send(data), // data: string | Uint8Array
  })

app.listen(3000) // Bun

Lifecycle

Every callback is optional - { message } alone is a valid echo server. upgrade is the only callback that runs before the socket opens, so it’s where a route rejects a connection or seeds its data.

TS
// doc-check: skip - illustrative lifecycle (empty close/error bodies, cookie shape).
app.ws<{ user: string }>("/chat", {
  // upgrade(c) runs in the full HTTP request context, BEFORE the socket opens, after the
  // guards registered before this route. Return the per-connection data (→ ws.data, typed),
  // or a Response or status(...) to REJECT the upgrade. A thrown Response rejects with it;
  // any other throw goes to onError, then a 500.
  upgrade(c) {
    const user = c.cookies.session
    if (user === undefined) return new Response("unauthorized", { status: 401 })
    return { user }
  },
  open: (ws) => ws.send(`welcome ${ws.data.user}`), // ws.data is { user: string }
  message: (ws, data) => ws.send(data),              // string | Uint8Array, normalized
  close: (ws, code, reason) => {},
  error: (ws, err) => {}, // a throw in any callback routes here, never crashing the connection
})

Guards

A handshake is a GET, and it runs the chain an HTTP GET registered at the same point runs: the authenticate() stages, derives and beforeHandles added before app.ws(), then upgrade. So auth middleware such as basicAuth or jwt guards the sockets registered after it, any guard can refuse the handshake with the response it would send an HTTP request, and upgrade reads what the guards derived. The origin check runs first. A socket registered before a guard stays public, like an HTTP route there. A browser cannot set a header on the handshake, so authenticate() can read a short-lived, single-use ticket from input.query - see Authentication runs first.

TS
// doc-check: skip - illustrative: an existing auth guard and session lookup.
app
  .ws("/status", {})                       // registered before the guard: public
  .authenticate(sessionAuth)               // or .use(basicAuth(...)), .derive(...), .beforeHandle(...)
  .get("/me", (c) => c.principal)
  .ws("/chat", {
    // Reached only when sessionAuth accepted the handshake, exactly as GET /me is.
    upgrade: (c) => ({ user: c.principal.id }),
  })

A socket declares the effects its code may reach with capabilities, as an HTTP route does. nifra capabilities check compares them with what the registering module can reach, and the handshake context carries the runtime guard for upgrade(). Reflection lists every socket under the pseudo-method "WS", so nifra assure classifies sockets too.

NifraWebSocket

The ws handed to each callback is a portable wrapper over the runtime’s native socket:

MemberWhat
send(data)text (string) or binary (ArrayBuffer/typed-array)
close(code?, reason?)close the connection; with no code it sends 1000, on every runtime
readyState0 CONNECTING · 1 OPEN · 2 CLOSING · 3 CLOSED
subscribe(topic) / unsubscribe(topic)pub/sub (below)
dataper-connection state, seeded by upgrade(), mutable
rawescape hatch to the native socket

Contract-validated messages

Inbound frames arrive raw (string | Uint8Array) by default. Add a messageSchema - any Standard Schema (t, zod, valibot) - and Nifra parses each frame as JSON, validates it, and hands message the typed value; anything that fails goes to onInvalidMessage instead (so a malformed frame can never reach your handler). nifra check reports NF-S009 (info) for a route whose message calls JSON.parse itself with no messageSchema.

TS
// doc-check: skip - illustrative: validated inbound frames on an existing app.
import { t } from "@nifrajs/schema"

app.ws("/chat", {
  messageSchema: t.object({ kind: t.literal("say"), text: t.string({ maxLength: 500 }) }),
  message(ws, msg) {
    // msg is typed { kind: "say"; text: string } - already parsed + validated.
    app.publish("room", msg.text)
  },
  onInvalidMessage(ws, issues) {
    ws.send(JSON.stringify({ error: "bad message", issues }))
  },
})

Optional outbound validation

sendSchema is type-level by default: it documents and types what the client receives with no runtime cost. Set validateSend: true to check server-sent JSON text and UTF-8 binary frames before the native socket sends them. Invalid frames and async validators fail closed and route a diagnostic to error when present. This is a contract check for your own output, not an inbound security boundary; the flag requires a sendSchema and is intentionally off by default.

TS
// doc-check: skip - illustrative: outbound contract on an existing app.
import { t } from "@nifrajs/schema"

app.ws("/events", {
  sendSchema: t.object({ kind: t.literal("ready"), id: t.string() }),
  validateSend: true, // opt in; default remains type-level only
  open(ws) {
    ws.send(JSON.stringify({ kind: "ready", id: "evt-1" }))
  },
})

Typed messages, end to end

Put both schemas in a module the server and the client import, each a t.union discriminated on a literal type. The server's message then switches over what the client sent, and the typed client's .ws() handle types send from messageSchema and every received frame from sendSchema. A default branch that assigns the frame to never turns a new server frame into a compile error on the client instead of a silently ignored message.

The client types received frames but does not check them unless asked: pass the route's sendSchema as validateReceive (the typed client carries the contract's types, not its schemas, so the schema is the import). A frame that fails is not delivered; onError gets a TypeError naming the issues, with the frame as its cause. Frames keep their arrival order, an async schema included.

TS
import { client } from "@nifrajs/client"
import { type InferOutput, server } from "@nifrajs/core/server"
import { websocket } from "@nifrajs/core/ws"
import { t } from "@nifrajs/schema"

// The contract, in a module both sides import: one discriminated union per direction.
export const ChatIn = t.union([
  t.object({ type: t.literal("say"), text: t.string({ maxLength: 500 }) }),
  t.object({ type: t.literal("pong"), id: t.integer() }),
])
export const ChatOut = t.union([
  t.object({ type: t.literal("said"), from: t.string(), text: t.string() }),
  t.object({ type: t.literal("ping"), id: t.integer() }),
])
type ChatFrame = InferOutput<typeof ChatOut>

const frame = (value: ChatFrame): string => JSON.stringify(value)

// Server: a ping every 30 s; a connection that leaves two unanswered is closed.
const app = server()
  .use(websocket())
  .ws("/chat", {
    messageSchema: ChatIn,
    sendSchema: ChatOut,
    upgrade: (c) => ({
      user: c.cookies.user ?? "guest",
      sent: 0,
      unanswered: 0,
      timer: undefined as ReturnType<typeof setInterval> | undefined,
    }),
    open(ws) {
      ws.subscribe("room")
      ws.data.timer = setInterval(() => {
        if (ws.data.unanswered >= 2) return ws.close(4000, "heartbeat timeout")
        ws.data.unanswered += 1
        ws.data.sent += 1
        ws.send(frame({ type: "ping", id: ws.data.sent }))
      }, 30_000)
    },
    message(ws, msg) {
      switch (msg.type) {
        case "say":
          app.publish("room", frame({ type: "said", from: ws.data.user, text: msg.text }))
          break
        case "pong":
          // Only an answer to a ping still outstanding counts, not any id the client makes up.
          if (msg.id > ws.data.sent - ws.data.unanswered && msg.id <= ws.data.sent) {
            ws.data.unanswered = 0
          }
          break
      }
    },
    close: (ws) => clearInterval(ws.data.timer),
  })

// Client: frames are typed from sendSchema, and checked against it with validateReceive.
export async function joinChat(baseUrl: string): Promise<void> {
  const chat = client<typeof app>(baseUrl).chat.ws({
    validateReceive: ChatOut,
    onError: (error) => console.warn(error),
  })
  for await (const msg of chat.messages()) {
    switch (msg.type) {
      case "said":
        console.log(`${msg.from}: ${msg.text}`)
        break
      case "ping":
        chat.send({ type: "pong", id: msg.id }) // a frame the client must answer
        break
      default: {
        const unhandled: never = msg // a new ChatOut variant fails to compile here
        throw new Error(`unhandled frame ${JSON.stringify(unhandled)}`)
      }
    }
  }
}

Frames the client must answer (heartbeats)

A server heartbeat that the application can see is an ordinary frame in the contract: a ping variant in sendSchema and a pong variant in messageSchema. The client answers it from the same switch that handles every other frame, so the answer is typed and the exhaustiveness check covers it; the server counts unanswered pings in ws.data, takes a pong only for a ping still outstanding, and closes a connection that stops answering, as above. Clear the timer in close. WebSocket protocol pings (the runtime's own keep-alive) are answered by the socket itself and never reach messages(); use them to keep a connection open through proxies, and a frame in the contract when the server needs to know the client is still running.

Pub/sub - app.publish

ws.subscribe(topic) joins a topic; app.publish(topic, data) broadcasts to everyone in it. Subscriptions drop automatically when a connection closes.

TS
// doc-check: skip - illustrative pub/sub on an existing app.
app.ws("/room/:id", {
  open: (ws) => ws.subscribe("room"),
  message: (ws, text) => app.publish("room", text), // fan out to all subscribers
})

Bun, Deno, and Node are long-lived processes, so this works directly on a single instance. Across a load balancer, app.publish only reaches sockets on the same instance - configure a TopicAdapter on server() to bridge a shared fan-out. On Cloudflare Workers, a stateless isolate can’t broadcast across connections, so Nifra ships a Durable Object hub: createWebSocketHub(app) holds the connections, and toFetchHandler(app, { webSocketHub }) routes upgrades to it - then ws.subscribe / app.publish behave exactly as on Bun. An upgrade request for a path with no WebSocket route still gets that path's HTTP answer, as on every other runtime.

TS
import { server } from "@nifrajs/core/server"
import { websocket } from "@nifrajs/core/ws"
import { sharedTopics } from "./shared-topics"

const app = server({ topicAdapter: sharedTopics })
  .use(websocket())
  .ws("/chat", { open: (ws) => ws.subscribe("room") })

await app.publish("room", "hello from any instance")

A TopicAdapter implements socket subscription cleanup and topic broadcasts. Its publish may return a promise; await app.publish when it does. The default in-process registry remains synchronous.

TS
// doc-check: skip - Workers entry: a Durable Object hub holds the connections.
import { toFetchHandler } from "@nifrajs/core/server"
import { createWebSocketHub } from "@nifrajs/workers"

export const NifraWebSocketHub = createWebSocketHub(app) // bind as NIFRA_WS_HUB in wrangler.toml
export default toFetchHandler(app, { webSocketHub: (env) => env.NIFRA_WS_HUB })

Serving - adapter-integrated, not app.fetch

A WebSocket upgrade can’t go through app.fetch(Request) - it needs the live socket, which only the runtime’s serving layer holds. So WS is wired by each serving entry; app.ws() and the handler are identical everywhere.

RuntimeServe withUpgrade primitive
Bunapp.listen(port)Bun.serve server.upgrade + websocket config
Denoserve(app, …) from @nifrajs/denoDeno.upgradeWebSocket
Nodeserve(app, …) from @nifrajs/nodethe upgrade event + the optional ws package
Cloudflare Workersexport default toFetchHandler(app)WebSocketPair + a 101 response

Node has no built-in WebSocket server, so @nifrajs/node uses ws - an optional peer dependency, lazy-imported on the first upgrade (a non-WS Node app never loads it). Install it when you use app.ws(); without it a WS upgrade gets a clean 501 and the HTTP routes are unaffected.

TS
npm i ws

nifra dev serves app.ws() routes too, on the Bun pipeline and under Vite, through each route's own upgrade() guard and Origin check. Under Vite the upgrade goes through Node's upgrade event, so it needs ws as well; without it a WS upgrade gets a 501 naming the package, and a path no WebSocket route takes stays with Vite's HMR.

server({ wsMaxPayloadBytes }) caps one inbound message (default maxBodyBytes, 1 MB): a socket that sends more is closed with 1009 and the message never reaches your handler. Bun and Node refuse it while it arrives. When a message passes Bun's own frame limit (the largest cap on the listener, below), Bun up to 1.4.3 drops the connection without a close frame, so the client sees 1006, and Bun 1.4.4 sends 1009; your close handler gets 1009 either way, as on every other runtime. Deno's Deno.upgradeWebSocket takes no size limit, so Deno receives each message whole (up to its own limit, 64 MiB on Deno 2.9) before nifra can check it: the cap still keeps the message from your handler, but it does not bound the memory Deno spent receiving it. Where that matters, cap message size in a proxy in front of a Deno app.

In a composed app

mount({ path, app }) carries WebSocket upgrades as well as HTTP: when the serving adapter sees an upgrade under the mount's path, it asks the child's resolveWebSocketUpgrade and upgrades its own socket with the outcome. Any nifra server with websocket() installed has one. A child that is not a nifra server can implement it too, building the outcome from @nifrajs/core/ws: attachWebSocket wires the socket to a handler and a TopicRegistry owns its pub/sub. On Bun, install websocket() on the parent or on a mounted nifra child, or listen() refuses to start with INVALID_WS_RUNTIME.

Each mounted nifra app keeps its own wsMaxPayloadBytes: a message over the child's cap closes that socket with 1009, whether the cap is below or above the parent's. On Bun one listener serves them all, so its frame limit is the largest cap among the parent and the apps mounted on it, and a socket whose app declares less checks its own.

mountFetch(path, handler) and a plain fetch handler carry HTTP only. An upgrade request under such a path reaches the handler as an ordinary request and never becomes a socket. Serve that path's WebSockets from a mounted child, or keep that server beside nifra.

TS
// server.ts - one listener; the chat child and a non-nifra child both take upgrades.
import { server } from "@nifrajs/core/server"
import { attachWebSocket, TopicRegistry, websocket, type WebSocketUpgradeOutcome } from "@nifrajs/core/ws"

const chat = server()
  .use(websocket())
  .ws("/room", { message: (ws, data) => ws.send(data) })

// Not a nifra server: it answers HTTP through fetch and builds its own upgrade outcome.
const topics = new TopicRegistry()
const legacy = {
  fetch: () => new Response("legacy"),
  resolveWebSocketUpgrade: (request: Request): WebSocketUpgradeOutcome =>
    new URL(request.url).pathname === "/feed"
      ? { kind: "upgrade", handler: { open: (ws) => ws.send("hello") }, data: undefined, pubsub: topics, attach: attachWebSocket }
      : { kind: "pass" },
}

server()
  .use(websocket()) // Bun: the parent holds the socket table every mounted upgrade runs through
  .mount({ path: "/chat", app: chat, stripPrefix: true })
  .mount({ path: "/legacy", app: legacy, stripPrefix: true })
  .listen(3000)