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 WebSocketconst kvStore = kv('connections').allow('get', 'set', 'delete')const socket = websocket('example-websocket')// Handle new connectionssocket.on('connect', async (ctx) => {await kvStore.set(ctx.req.connectionId, {/* connection meta data here */})})// Handle disconnectionssocket.on('disconnect', async (ctx) => {const disconnectedId = ctx.req.connectionIdawait kvStore.delete(disconnectedId)})
Sending Messages
import { websocket, kv } from '@nitric/sdk'// Initialize KV store for connections and a WebSocketconst kvStore = kv('connections').allow('get', 'set', 'delete')const socket = websocket('example-websocket')// Handle new connectionssocket.on('connect', async (ctx) => {await kvStore.set(ctx.req.connectionId, {/* connection meta data here */})})// Handle disconnectionssocket.on('disconnect', async (ctx) => {const disconnectedId = ctx.req.connectionIdawait kvStore.delete(disconnectedId)})// Send messagessocket.on('message', async (ctx) => {const message = ctx.req.text()const connections = kvStore.keys()// Send the message to each connectiontry {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
Cloud Service Mapping
Each cloud provider comes with a set of default services used when deploying resources. You can find the default services for each cloud provider below.
- AWS
- Azure - Not implemented
- Google Cloud - Not implemented
If you need support for additional clouds, let us know by opening an issue or joining the conversation on Discord.