createWebSocketOutbox
Keep messages until the server acknowledges them, across reconnects and page reloads. Each message is stored (in IndexedDB by default) and sent with an idempotency key, and sent again on every new connection until the server acknowledges that key.
Available only from react-websocket/outbox. It has no React dependency, and its size (about 1.1 kB min+gzip) is separate from the main entry's. List its entries in React with useWebSocketOutbox.
Usage
Annotate send's message parameter: that's what outbox.add() accepts. The guide is Offline outbox.
Parameters
Returns
A WebSocketOutbox<M>:
OutboxEntry
OutboxStorage
react-websocket/outbox exports two: indexedDBStorage(name), the default, and memoryStorage(), which keeps entries in memory only, for tests. Write your own to keep entries somewhere else, such as a native app's storage. Messages must survive whatever your storage does to them: IndexedDB stores anything the structured clone algorithm can copy.
Behavior
- At least once. An entry is sent when it's added if the socket is open, and again on every new connection until the server acknowledges its id, including after
migrate(). The server must handle an id it has already seen by acknowledging it again, without acting twice. - In order. Entries are sent oldest first. After a reload, nothing is sent until the stored entries are back, so they go before new ones.
- Holds the connection. While entries are waiting, the outbox holds the client's connection open, as a mounted hook would, so they're delivered even if no component uses the client.
- Not the client's queue. Entries are sent only while the socket is open, and resent by the outbox itself, so
queueoptions andsend()options don't apply to them. They go out from anopenlistener, ahead of the client's own queue. Over WebTransport they go on the reliable stream, never as datagrams. - Tabs. Each tab loads the stored entries when its outbox is created and sends them, so two open tabs can both send an entry. The idempotency key makes that harmless. Tabs tell each other over a
BroadcastChannelnamed after the outbox when an entry is acknowledged or removed, or the outbox cleared, so the others drop it too. - The database. The IndexedDB connection closes when another page deletes or upgrades the database, and opens again on the next write.
- Errors. If
sendthrows, the error surfaces where it was called: fromadd(), or asynchronously on a new connection.