Back

Build real-time applications with Nitric πŸ”Œ

Nitric and websockets logo
Tim HolmTim Holm

Tim Holm

2 min read

I'm really excited to announce that we've released support for building websocket applications in the Nitric framework!

This unlocks a whole range of use cases when building with Nitric by allowing all kinds of real-time interaction as well as supercharging websockets by seamlessly integrating them with other Nitric resources such as topics, buckets, queues, and more.

With this you could start building backends for chat applications and bots, multiplayer apps, realtime notifications and have it deployed in your own cloud in a matter of minutes!

Getting started with websockets is super simple. If you'd like more detail you can check out our docs here.

import { websocket, collection } from "@nitric/sdk";

const connections = collection('connections').for('reading', 'writing', 'deleting');
const socket = websocket('socket');

socket.on('connect', async (ctx) => {
    await connections.doc(ctx.req.connectionId).set({});
});

socket.on('disconnect', async (ctx) => {
    await connections.doc(ctx.req.connectionId).delete();
});

socket.on('message', async (ctx) => {
    const allConnections = await connections.query().stream();

    const streamEnd = new Promise<any>(res => allConnections.on('end', res));

    allConnections.on('data', async (connection) => {
        if (connection.id !== ctx.req.connectionId) {
            await socket.send(connection.id, ctx.req.data);
        }
    });

    await streamEnd;
});

This is all you need to get a simple chat application going 🀯

Want to see a bigger example in action? Check out a fun example where I used Nitric websockets as a signalling server to build a multiplayer gameboy using WebRTC.

At this time we've released this in the Node.js SDK and it's soon to be implemented in our other SDKs.

Currently we support AWS deployments and local development for websockets. If you'd like to see us expand this capability to other providers let us know in our Discord or in our core Github Repo.

Previous Post
Nitric Update - July 2023
Next Post
Enhance Express.js, Koa, Fastify and other web frameworks with Nitric