neffos.js is the official client library for the neffos real-time WebSocket framework, written in TypeScript and shipped with full type definitions.
It runs in browsers, in Node 22 and newer, in Deno and Bun, in web workers, and inside bundlers such as esbuild, webpack and Vite. Code samples are at _examples/.
npm install neffos.jsimport * as neffos from "neffos.js";const neffos = require("neffos.js");Types are bundled with the package. No separate @types/* install is needed.
// Deno: the npm specifier, no install step.
import * as neffos from "npm:neffos.js";bun add neffos.js # then import it like any ESM packageThe exports map serves one build per condition: dist/neffos.js (ESM) for import, dist/neffos.cjs for require, dist/neffos.browser.js when a bundler resolves the browser condition, and the two script-tag builds as subpaths, neffos.js/global and neffos.js/global.min. Every build has a source map, the package is marked sideEffects: false so a bundler can tree-shake what you do not call, and the types in dist/neffos.d.ts are generated from the TypeScript source, so they cannot drift from it.
<script src="https://cdn.jsdelivr.net/npm/neffos.js@0.3/dist/neffos.global.min.js"></script>
<script>
neffos.dial("ws://localhost:8080/echo", { /* ... */ }).then((conn) => {
// top-level await is not available in a plain <script> tag.
});
</script><script type="module">
import * as neffos from "https://cdn.jsdelivr.net/npm/neffos.js@0.3/+esm";
const conn = await neffos.dial("ws://localhost:8080/echo", { /* ... */ });
</script>Pin the version to your release rather than @latest in production.
| Runtime | WebSocket it uses | Handshake headers |
|---|---|---|
| Browsers, Deno, Bun, web workers | the native WebSocket |
sent as X-Websocket-Header-<name> URL parameters, since none of these let you set custom headers on a websocket handshake |
| Node 22 and newer, no extra install | the built-in global WebSocket |
same as above: URL parameters |
Node, with the optional ws package |
pass { WebSocket: require("ws").WebSocket } in Options |
sent as real HTTP headers |
Node 20 is not supported. engines.node in package.json requires >=22. The
ws package is an optional peer dependency: install it only if you want real
headers, or if you are on a Node version without a global WebSocket.
A header sent as a URL parameter lands in the server's access log and in any
proxy between. Put a short-lived token there, not a long-lived credential, or
run the handshake through ws on the server-to-server side where real headers
are available. On the Go side neffos.URLParamAsHeaderPrefix is the prefix
the server strips.
import * as neffos from "neffos.js";
const conn = await neffos.dial("ws://localhost:8080/echo", {
default: {
[neffos.OnNamespaceConnected](ns, msg) {
console.log("connected to namespace:", msg.Namespace);
},
[neffos.OnNamespaceDisconnect](ns, msg) {
console.log("disconnected:", msg.Namespace);
},
async chat(ns, msg) {
console.log("server says:", msg.text());
},
},
});
const ns = await conn.connect("default");
ns.emit("chat", "Hello from the client!");The system events are exported as constants (OnNamespaceConnect,
OnNamespaceConnected, OnNamespaceDisconnect, OnRoomJoin, OnRoomJoined,
OnRoomLeave, OnRoomLeft, OnAnyEvent, OnNativeMessage), so a typo is a
compile error instead of a handler that never fires. The string form,
_OnNamespaceConnected, still works.
Handlers may be synchronous or async. A handler can return nothing, an
Error (sent back to the server as the event's error), or throw; a thrown
error is caught and sent back the same way.
marshal(obj) turns a value into a JSON body and msg.unmarshal<T>() reads one back. The matching Go server side is c.SendObject(event, v) to send and msg.As[T]() to read, with neffos.ReplyObject(v) for a typed reply to ask:
interface Profile { id: number; name: string; tags: string[] }
ns.emit("save", neffos.marshal({ id: 42, name: "makis", tags: [] }));
const reply = await ns.ask("profile", neffos.marshal({ id: 42 }));
const profile = reply.unmarshal<Profile>();// the Go handler behind "profile", neffos v0.0.25
"profile": func(c *neffos.NSConn, msg neffos.Message) error {
req, err := msg.As[ProfileRequest]()
if err != nil {
return err
}
return neffos.ReplyObject(profiles.Load(req.ID))
},The server encodes with Go's encoding/json/v2, so an empty Go slice arrives as [] and an empty map as {}; a null only shows up for a nil pointer. Field names match case-insensitively on the Go side, so {"Name": ...} and {"name": ...} both bind.
A matching neffos Go server for this client lives at kataras/neffos/_examples/01-getting-started, and a full example tree including the server is at _examples/.
const conn = await neffos.dial(endpoint, handlers, {
headers: { Authorization: "Bearer ..." },
protocols: "chat-v1",
reconnect: 1000, // or a ReconnectOptions object, see below
timeout: 10_000, // the first dial (including its retries) must finish within this
signal: abortController.signal,
askTimeout: 5_000, // default timeout for every ask() that does not set its own
WebSocket: undefined, // defaults to globalThis.WebSocket, then the ws package; pass ws's WebSocket for real headers
onError: (err) => console.error(err),
});onError receives errors that have no caller to reject: an invalid frame, an
event for a namespace that was never connected, and a failed restore after a
reconnect. Without it, reconnect failures are logged with console.warn and
the rest are dropped silently.
ask is the request/response primitive. The server replies with the same
event name; the body is whatever the handler returned via neffos.reply(body).
const reply = await ns.ask("getProfile", "user-42");
console.log(reply.text());// AskOptions: a per-call timeout and an AbortSignal.
const reply = await ns.ask("getProfile", "user-42", { timeout: 3000 });timeout defaults to Options.askTimeout (0 waits forever) and rejects with
a NeffosError whose code is ERR_TIMEOUT. Aborting signal rejects with
the signal's reason. conn.ask(msg, options?) takes the same options for a
raw Message.
ns.emitBinary("upload", new Uint8Array([1, 2, 3]));
const reply = await ns.ask("upload", new Uint8Array([1, 2, 3]));
console.log(reply.bytes()); // Uint8ArrayemitBinary is on both NSConn and Room. A Message.Body is
string | Uint8Array; msg.text() decodes bytes as UTF-8 if needed, and
msg.bytes() encodes a string as UTF-8 if needed, so a handler can call
either one regardless of how the frame arrived.
Every error this library creates is a NeffosError (extends Error), with a
stable code such as ERR_BAD_NAMESPACE or ERR_TIMEOUT:
try {
await conn.connect("unknown-namespace");
} catch (err) {
if (err instanceof neffos.NeffosError) {
console.log(err.code); // "ERR_BAD_NAMESPACE"
}
}The shared sentinels ErrInvalidPayload, ErrBadNamespace, ErrBadRoom,
ErrClosed and ErrWrite are NeffosError instances whose message text
matches the Go server's, so an error that travels over the wire resolves back
to the same object on the client: err === neffos.ErrBadNamespace works.
CloseError is a NeffosError that closed, or asked to close, the
connection; its message is "[code] text", the form the Go server sends for
a server-side close, for example "[-1] write closed". isCloseError(err)
reports whether an error came from a shutdown or a forced close, rather than
from application code. registerKnownError(err) adds your own shared error
so a matching error frame resolves to that same instance instead of a plain
Error.
const conn = await neffos.dial(endpoint, handlers, {
reconnect: 1000, // or: { initialDelay: 1000, maxDelay: 30000, factor: 2, maxRetries: 10 }
});A number is shorthand for { initialDelay: <number> }; 0 turns reconnect
off. The delay grows by factor each retry (default 2), capped at maxDelay
(default 30000 ms), with up to jitter (default 0.2, so 20%) shaved off at
random so that many clients do not all retry in the same instant.
maxRetries is unlimited by default. shouldReconnect(info) gets the close
code, reason and wasClean flag of each drop and can veto the retry, for
example after a 4003 your server uses for "banned". probe: true sends an
HTTP HEAD to the endpoint before each retry and only redials once it
answers, which is what 0.2.0 always did; it is off by default.
The same Conn is reused after a reconnect: conn.isClosed() stays false,
and application references to a connected NSConn or a joined Room keep
working once the restore finishes. Namespaces reconnect one at a time, each
followed by its rooms, in the order they were connected before the drop.
conn.wasReconnected() and conn.reconnectTries report whether and how many
times this happened. Call conn.close(), or abort Options.signal, to stop
reconnecting.
| Export | Shows |
|---|---|
Message |
one frame: Namespace, Room, Event, Body, Err, plus text(), bytes() and unmarshal<T>() |
Room |
a joined room: emit, emitBinary, leave() |
NSConn |
a connected namespace: emit, emitBinary, ask, joinRoom, room, roomNames, leaveAll, disconnect |
Conn |
the connection itself: connect, waitServerConnect, namespace, ask, write, close, isClosed, wasReconnected, reconnectTries, closeInfo, ID |
NeffosError |
the base class of every error this library creates, with a code |
CloseError |
a NeffosError that closed, or asked to close, the connection, with closeCode and cause |
dial(endpoint, connHandler, options?) |
opens a connection and resolves with a Conn |
marshal(obj) |
serializes an object to a string for use as a Message.Body |
reply(body) |
return this from a handler to echo body back to the sender on the same event |
isCloseError(err) |
true if err came from a server shutdown or a forced close |
registerKnownError(err) |
shares a custom error so both sides resolve the same instance |
isSystemEvent(event) |
true for the built-in connect, disconnect and room events |
OnNamespaceConnect ... OnNativeMessage |
the nine system event names, for use as handler keys |
ErrInvalidPayload, ErrBadNamespace, ErrBadRoom, ErrClosed, ErrWrite |
the shared sentinels, the same instances the wire resolves to |
ReplyError |
what reply(body) returns; a handler that returns it sends body back as a normal message |
URLParamAsHeaderPrefix |
X-Websocket-Header-, the prefix headers get when they travel as URL parameters |
| types | Options, ReconnectOptions, AskOptions, CloseInfo, Namespaces, Events, MessageHandlerFunc, ConnHandler, WSData, Headers, WebSocketLike, WebSocketConstructor, ErrorResolver |
See HISTORY.md for every release, including what changed and why.
neffos.js follows Semantic Versioning 2.0.0. neffos.js
0.3.x speaks the same wire protocol as every neffos (Go) v0.0.x server, v0.0.25
included: any of those server versions works with this client, and the client's
own version does not need to track the server's.