Repository navigation
Releases
4.22.3
The library's code is the same as in 4.22.2. This release updates the examples' dependencies to fix published
security advisories.
Documentation
- The Hono and Astro examples use dependency versions that fix published security advisories:
hono4.13.17 and
@hono/node-server2.1.6 in the Hono example, andastro7.4.8 with@astrojs/node11.1.11 in the Astro
example.
4.22.2
This release fixes bugs in how the client, its managers and the socket wrappers move between states: what they do
when a connection drops, closes or switches while something else is under way.
Fixed
reconnect()afterclose()takes back the hold ofconnect(): a client started withconnect()stays connected
again untilclose(), even with no hook holding it. It used to close the new connection 5 seconds after it
opened.- A client closed, or one that gave up, in the few seconds after a connection nobody held opened (such as one a
Suspense render started) stayscloseduntil the next hook holds it. It used to turnidlewhen those seconds
ran out, and readingreadythen connected it again afterclose(). - A request made while the socket isn't open, on a client created with
queue: false(orqueue.limit0), rejects
right away and sends nothing, like a volatile one. It used to wait for its timeout, forever with
timeout: Infinity, and then send a cancel for an id the server never got. - A request that starts a client which fails at once, such as one with an invalid URL, rejects as on a closed
client instead of waiting in the queue. A request made afterdispose()rejects instead of going out with nothing
listening for its reply. - A
timeoutlonger thansetTimeoutcan wait, about 24.8 days, waits forever in requests and in the responder.
It used to time out at once. - The responder answers a request only on the connection it arrived on. During a
migrate()switch, a reply, or a
request that an asyncschemadelivered late, could reach the new connection, where the server doesn't know the
id. - A topic acquired on a socket that had just opened, from a store listener or an earlier
openlistener, is
subscribed once, not twice. - When the connection drops, only the runs that were streaming on it are aborted. A run that a listener started
meanwhile, such as the next prompt in a queue, was aborted with them, so a queue drained itself. - A run that a listener ends as soon as it starts no longer sends a resume and holds the connection for good.
- Presence forgets the other peers when the client closes, so
close()on logout doesn't leave the previous user's
peers on screen until they time out. It refreshes only after a send that went out, so no timer runs while
disconnected, andset()afterdispose()no longer starts a refresh that never stops. - Latency doesn't start its ping interval when an earlier
openlistener already closed the connection. - The outbox sends each entry once per connection. An
add()from anopenlistener that ran before the outbox's
own used to send everything again. An entry removed, sent or replaced during a flush, for example byonExpire,
is no longer sent or brought back by it.remove()andclear()afterdispose()delete from storage instead of
throwing. - AG-UI: a chunk without a
messageIdcontinues its message past the activity events between chunks, instead of
going to the activity message. An aborted run shows no step, and a new run doesn't start with the last one's
step, error or result. A run followed again after a reload shows as running until its events replay, and as
aborted if it was stopped meanwhile. - After a reconnect, the timeline doesn't take latency measured on the previous connection as the server's clock,
which pinnedrenderTime()to a restarted server's old clock. react-websocket/webtransport: a fallbackWebSocketthat throws, for example on protocols it rejects, or a
Blobthat can't be read, fails the connection with anerrorand a1006close. It used to leave the socket
connecting forever, or drop every later send. A session that fails no longer leaves an unhandled promise
rejection, which error trackers reported on every fallback.react-websocket/chaos:close()with a reason over 123 bytes throwsSyntaxError, like a browser, where it used
to leave the socket closing for good. A stall also holds back the sends still delayed bylatency. With
latency, a page in a background tab no longer falls behind until its heartbeat gives up: browsers hold its timers
back by a second to a minute, solatencynow pauses while the tab is hidden.react-websocket/replay: the recorder'sclose()with a code the browser rejects throws and leaves it open, where
it used to leave it closing and ignoring its messages. A replay'sdoneresolves after the lastcloseevent,
not before it.react-websocket/tabs: the shared connection closes once its last socket does, even after a tab's socket closed
while its connect was on the way. Thepagehidelistener is removed once no socket is open, and a tab disposed
while waiting to lead no longer throws when it takes over.
4.22.1
The library's code is the same as in 4.22.0. This release corrects the author details npm shows, and updates the
examples.
Changed
- The package's author and maintainer are now
Mehmet Kose <mehmetkose@duck.com>with
mehmetkose.github.io, replacing an email address and website that were wrong.
Documentation
- The Next.js, Astro and Remix examples use dependency versions that fix published security advisories:
next
16.4.2 andzod4.6.7, and in the Astro exampleundici8.12.3,qs6.16.1,body-parser2.4.0 andfast-uri
3.1.9. The Remix example overridesesbuildto 0.28.2, sinceremixstill asks for 0.27. - The Hono example and
its recipe use what 4.22.0 documented. Chat
messages are requests the server answers withpostedorrefused, and a retry with the same key isn't posted
twice. The server tells clients when to come back: a full room closes with1013and a delay, long-lived
connections are asked tomigrate(), and a page built for an older protocol is closed with a code it doesn't
retry, and asks the user to reload. A newbot.tsjoins from Node with a token in a header, through a proxy if
HTTPS_PROXYis set.
4.22.0
The library's code is the same as in 4.21.0. This release adds documentation that came from comparing the client
with Faye's.
Documentation
- Publishing with an acknowledgement,
a new pattern in the recipes: publish to a topic and await the server's answer withcreateWebSocketRequests,
tell a refusal from an answer that never came, retry without publishing twice, and use the outbox instead for
messages that must survive a reload. - Letting the server decide,
a new section in the reconnecting guide: how a server tells clients to come back later, start over on a new
connection, or not come back, the three kinds of reconnect advice Bayeux servers such as Faye give, with the close
codes and messages that carry them. - Headers, proxies and TLS
in Node: awssubclass that sends headers with a fresh token on every connection, connects through a proxy,
trusts a private certificate authority, and ends attempts that hang, which neither the client norwsdoes on
its own when a proxy doesn't answer.
4.21.0
Security
Logging out, or another user signing in on the same page, no longer has to carry the previous user's data or queued
messages into the next user's session. Before, the documented steps (close() on logout, reconnect() on an account
switch) reset only the socket: the next user could see the previous user's last message, feed positions, runs and
agent thread, and could send their queued outbox entries. See
Logging out and switching accounts.
Added
feeds.reset(topic?)forgets the position of a topic, or of every topic, so the next subscription starts from the
beginning instead of from the previous user's last message.runs.clear()forgets every run, in memory and in storage, including unsent starts and pending cancels. It sends
nothing.agent.reset()(AG-UI) forgets the thread, starts the next run fromstate, and picks a new thread id unless one
was given.createTabsWebSocket({ session }): tabs share a connection only with tabs that return the same session, such as
the user's id, so the next user gets a connection of their own.
Changed
close()also clearslastMessage, as it already cleared the send queue and amigrate()target. Components
that renderlastMessageshowundefinedafterclose()until a message arrives.
Fixed
outbox.clear()removes every entry that exists when it's called. It used to keep entries whose timestamps were
ahead of the clearing tab's clock, as after the clock is set back or after another tab added many entries at once,
and they were then sent on the next connection.
Documentation
- The authentication guide covers logging out and switching accounts: call
close()and reset what the managers
keep, thenconnect(), rather thanreconnect(), which keeps the send queue. Servers should close a user's open
sockets when their session ends.SECURITY.mdsays the same. - The recipes' servers check every message before using it: JSON, a known
type, and the fields that type needs.
Anything else closes only that client's socket with1003, which the client doesn't retry, where a malformed
message used to throw and stop the whole server. Every server socket gets anerrorlistener, and the voice
assistant's connection to the provider does too. - The live notifications recipe refuses to start without a
SOCKET_SECRETof at least 32 characters, where it used
to sign tokens with an empty key that anyone could reproduce.verifyTokenrejects tokens that aren't strings or
don't have three parts, and compares the signatures' bytes, not their characters. - The team chat, collaborative whiteboard and delivery tracking recipes clear their outbox on sign-out, and the live
notifications recipe also forgets its feed position. - The Next.js, Astro and Remix examples' demo servers survive malformed messages, limit messages to 64 KiB, accept
only palette colors and on-pad cursor positions, and their cursors paint the color withbackgroundColor, so a
peer can't make other viewers' browsers load a URL.
4.20.0
The library's code is the same as in 4.19.1. This release adds framework recipes to the documentation.
Documentation
- Framework recipes under Recipes, one for each
example: Next.js,
Astro,
Remix 3,
Hono and
Tornado. Each one shows where the shared client
goes, where the WebSocket server goes in that framework, and how to run the example. The sidebar has a new
Frameworks group, and each example's README links to its recipe.
4.19.1
Changed
- The published files no longer read
process.env, which security scanners such as Socket flag as environment
variable access.react-websocketships a production build without the development-only checks, and a development
build with them, which tools load through thedevelopmentcondition inexports. Vite, Vitest, webpack and
Next.js load it in development. Other tools load the production build unless you add the condition; see
No warnings in development.
4.19.0
The library's code is the same as in 4.18.1. This release updates the Tornado example.
Documentation
- The Tornado example's server runs with
uv:npm run example:tornado:serverisuv run examples/tornado/server.py, which reads the dependencies from the
script and pins them inserver.py.lock(Tornado 6.5.10, Python 3.11 or later). The server accepts pages from
localhostonly, where it used to accept any origin. It pings clients to drop dead connections, caps messages at
64 KiB, and relays binary messages as binary.
4.18.1
The library's code is the same as in 4.18.0. This release brings the new README and package description to npm.
Documentation
- The README and the package description present react-websocket as a real-time toolkit: install and a quick start
come first, then the features and the API, grouped into the core and six opt-in groups. The bundle size is now given
as about 4 kB, which is what{ useWebSocket }measures. - Real-world guides that build whole apps, client and server: an AI chatbot, an AI image and video generator, a voice
assistant, a multiplayer party game, a real-time action game, a team chat, a collaborative whiteboard, a trading
dashboard, live notifications and delivery tracking. See
Real-world guides. - Numbered feeds: the example server sends the whole state when a client's
afteris ahead of its own number, as it
is after the server restarts. - Tabs share a connection only when they connect to the same URL, so a token in the URL that differs between tabs
opens a connection per tab. Send it in a first message instead.
4.18.0
Fixed
use(useWebSocket(url).client.ready)resolves. React retries a render that suspended without its state, so each
retry made a new client and waited for that one instead: in Chrome, 243 sockets in 4 seconds. The retry now gets
the client the first attempt started.client.close()with a code the browser rejects, such as1001, throws before anything changes. It used to throw
halfway, leaving the statusopen,socketnull and the real socket open, with its messages ignored.- A client closed, or one that gave up, while nothing held it starts again for the next hook to mount, as after the
last hook unmounted. It used to stayclosedfor good. migrate()delivers a message the old connection received while an asyncschemawas still validating it.- The client connects in a Web Worker, which has no
window. - Topics send nothing while the server closes the socket, which still reads
openuntil its close event. A release
and hold there used to be queued, and sent after the new connection's subscriptions: the server ended up
unsubscribed from a topic still held. - A request on a
closedclient rejects and leaves it closed. It used to move it toidle, so the next request
opened it again. - The library's own messages that must arrive go on WebTransport's stream, never as datagrams that can be lost:
outbox entries, request cancels, responder replies, feed resumes and AG-UI resyncs. In Chrome, outbox orders went
as datagrams. runs.start()with the id of a run it knows starts nothing. With an ended run's id, it used to reset its value to
'', keep it ended, and hold the connection open for good.- A
cancelrun'scancelis sent withqueue: falsetoo. - A duplicated tab, or one opened with
window.open, no longer cancels thecancelruns of the page it was copied
from: a page waits 200 ms for another to say it still follows a remembered run before cancelling it. The original
page used to show the cancelled run as streaming forever. - AG-UI asks for a snapshot again each time a delta fails after one, not only the first time in a run, and a run
that finished stale no longer makes the next run skip its deltas. applyPatchrejects an array'slengthas a member (replace /list/lengthused to truncate the array) and
pointers that don't start with/, and adds__proto__as a key of its own.- Outbox, without
ack: a message sent right away is no longer stored. Its delete could run before its write, so it
stayed stored and was sent again on the next page load. outbox.remove(),outbox.clear()and acknowledgements reach the other tabs' outboxes with the samename, which
drop the entry too. After aclear()in one tab, another used to send what it had loaded.- Outbox
add()resolves once IndexedDB has committed the write, and its database connection closes when another
page deletes or upgrades the database, which it used to block. - Tabs: a tab that closes lets go of the shared connection and its topics on
pagehide. The leader used to keep
both for it: the last live tab's unsubscribe was swallowed, and the shared socket stayed open. - Tabs: with
json, thetopicsfunctions only get messages that parse, and one that throws counts as no topic. The
guide's example threw on a heartbeat'ping', which never reached the server. - Tabs, where the Web Locks API is missing:
binaryType: 'arraybuffer'is honored, instead of always aBlob. - WebTransport:
close()while connecting reports its own code, not1006.
Documentation
<Activity>: a component usinguseWebSocket(url)keeps its client, and itslastMessage, across hide and show.- Suspense: a connection started only by reading
readykeeps retrying a server that's down until it opens, gives up
orclose()is called, since the client can't tell an abandoned read from a suspended render. - WebTransport: some server libraries, such as aioquic's event API, only see the client's stream once it writes, so
they can't send first.
This is the first release on npm since 4.0.0. It also includes 4.1.0 through 4.17.0, which were versioned in the changelog but not published; see the changelog for what each one changed.