Websockets

Nitric provides support for serverless websockets. This feature allows you to connect client applications to your Nitric services using websocket gateways such as AWS APIGateway.

Projects with websockets will only be deployable to AWS at the moment. If you require support for additional clouds let us know: https://github.com/nitrictech/nitric/issues

Listening for events

There are three events that must be defined to deploy a valid websocket implementation. These are connect, disconnect and message.

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
})

Managing connections

Nitric connects your services to a websocket interface, but it is up to you to manage the connections. Nitric provides kv out of the box that can be used to do this or you can use any other store or database you like.

import { websocket, kv } from '@nitric/sdk'
// Initialize KV store for connections and a WebSocket
const kvStore = kv('connections').allow('get', 'set', 'delete')
const socket = websocket('example-websocket')
// Handle new connections
socket.on('connect', async (ctx) => {
await kvStore.set(ctx.req.connectionId, {
/* connection meta data here */
})
})
// Handle disconnections
socket.on('disconnect', async (ctx) => {
const disconnectedId = ctx.req.connectionId
await kvStore.delete(disconnectedId)
})

Sending Messages

import { websocket, kv } from '@nitric/sdk'
// Initialize KV store for connections and a WebSocket
const kvStore = kv('connections').allow('get', 'set', 'delete')
const socket = websocket('example-websocket')
// Handle new connections
socket.on('connect', async (ctx) => {
await kvStore.set(ctx.req.connectionId, {
/* connection meta data here */
})
})
// Handle disconnections
socket.on('disconnect', async (ctx) => {
const disconnectedId = ctx.req.connectionId
await kvStore.delete(disconnectedId)
})
// Send messages
socket.on('message', async (ctx) => {
const message = ctx.req.text()
const connections = kvStore.keys()
// Send the message to each connection
try {
for await (const connectionId of connections) {
await socket.send(connectionId, message)
}
} catch (error) {
console.error('Error during message broadcasting:', error)
}
})

Do not send messages to a connection during it's connect callback, if you need to acknowledge connection, do so by using a topic

Last updated on Nov 11, 2024