Real-Time

WebSockets

Dependency-free RFC 6455 WebSocket server with rooms, guards and heartbeats. Server-only; connect with Node's global WebSocket or any client.

2 min readUpdated DocumentationEdit this page
On this page6

Setup

WSServer attaches to the app's http.Server, which exists once listen() has resolved.

TypeScript
TS
1import { Application } from '@axiljs/core'
2import { WSServer } from '@axiljs/websocket'
3
4const app = new Application()
5await app.listen(3000)
6
7const wss = new WSServer(app.getServer()!, { path: '/ws' })
8
9wss.on('connection', (client, request) => {
10  client.sendJSON({ type: 'welcome', id: client.id })
11
12  wss.join(client, 'chat')
13
14  client.on('message', (data, isBinary) => {
15    wss.toRoomJSON('chat', { from: client.id, text: data.toString() })
16  })
17})

Options

OptionDefaultDescription
path'/ws'URL path that accepts upgrades
maxClientsunlimitedFurther upgrades get 503
guardaccept all(request) => boolean | Promise<boolean>; false rejects with 403
maxPayload16 MiBMax frame / message size; larger closes with 1009
closeTimeoutMs5000Destroy the socket if the peer doesn't answer a close frame in time
heartbeatIntervalMs30000Ping interval; clients that miss a pong are terminated. 0 disables

Upgrades on other paths

An upgrade request for a different path is left alone when another upgrade listener is attached to the same server (for example a second WSServer on another path). When this WSServer is the only upgrade listener, it answers 404 Not Found and closes the socket, so clients don't hang waiting for a response.

Server-side client API

Each connection is a WSClient:

TypeScript
TS
1client.id
2client.remoteAddress
3client.send('text')
4client.sendJSON({ type: 'data' })
5client.sendBinary(buffer)
6client.ping()
7client.close(1000, 'reason')
8client.terminate()
9client.isOpen

Events: message (data, isBinary), close (code, reason), error, ping, pong.

Broadcasting and rooms

TypeScript
TS
1wss.broadcast('plain text')
2wss.broadcastJSON(data)
3wss.broadcastJSON(data, [excludeId])
4wss.join(client, 'room')
5wss.leave(client, 'room')
6wss.toRoomJSON('room', data)
7wss.getRoomClients('room')
8wss.getRooms()
9wss.clientCount
10wss.close()   // 1001 'Server shutting down'

Connecting from a client

Note

@axiljs/websocket is server-only: WSClient is the server's handle on an accepted connection, not an outbound client. Connect with the browser's WebSocket, Node's global WebSocket (Node 22+), or any RFC 6455 client library.

TypeScript
TS
1// Browser, or Node 22+ (global WebSocket)
2const ws = new WebSocket('ws://localhost:3000/ws')
3
4ws.addEventListener('open', () => {
5  ws.send('hello')
6})
7
8ws.addEventListener('message', (event) => {
9  const msg = JSON.parse(String(event.data))
10  console.log(msg.type, msg)
11})

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY