Node.js - websocket.on()
Register a handler for connections, disconnections, or messages for the websocket.
import { websocket } from '@nitric/sdk'const socket = websocket('socket')socket.on('connect', async (ctx) => {// handle connections})socket.on('disconnect', async (ctx) => {// handle disconnections})socket.on('message', async (ctx) => {// handle messages})
Parameters
- Name
eventType
- Required
- Required
- Type
- string
- Description
The type of websocket event to listen for. Can be
connect
,disconnect
, ormessage
.
- Name
middleware
- Required
- Required
- Type
- WebsocketMiddleware<T>
- Description
The middleware function(s) to use as handlers for the Websocket events.
Examples
The connect
event
The connect
event can be used to permit or deny new connections. Until the connect
handler returns a successful response the client will be unable to send or receive messages via the websocket. If you need to perform any sort of client authentication before accepting the connection this is where it should be done.
Unlike the other websocket events the connect
event has access to the query parameters provided during the connection request. This allows the client to provide relevant information needed to validate and establish the connection.
Additionally, the connectionId
provided during this event will be used for all future communication with the client via this connection, it should be persisted in your application until the connection is terminated.
import { websocket, kv } from '@nitric/sdk'import { isValidConnection, registerConnection } from 'lib/connections'const socket = websocket('socket')socket.on('connect', async (ctx) => {if (!isValidConnection(ctx.req.query)) {// deny the connectionctx.res.success = falsereturn}registerConnection(ctx.req.connectionId)})
Managing websocket connections
Websocket connections need to be managed. This can be done using any persistent data store you like. One approach is to use a Nitric key value store.
import { websocket, kv } from '@nitric/sdk'const socket = websocket('socket')const connections = kv('connections').allow('get', 'set', 'delete')socket.on('connect', async (ctx) => {const connectionList = await connections.get('connections')await connections..set('connections', [...connectionList,{// store any metadata related to the connection hereconnectionId: ctx.req.connectionId,},])})socket.on('disconnect', async (ctx) => {const connectionList = await connections.get('connections')await connections.set('connections',connectionList.filter((c) => c.connectionId === ctx.req.connectionId))})
Register a handler for message events
socket.on('message', async (ctx) => {// handle messagesconsole.log(`new message from ${ctx.req.connectionId}: ${ctx.req.data}`)})