Configuring WebSockets on Node/Express

This section will explain how to configure WebSockets on a Node/Express server. We will cover basic and advanced configuration topics such as connections, namespaces, rooms and more.

The following is an extremely basic configuration to get you started. It will simply emit a welcome message each time a client connects.

const express = require('express');
const http = require('http');
const io = require('socket.io');

const PORT = process.env.PORT || 3000;

const app = express();
const server = http.createServer(app);
const socket = io(server);

socket.on('connection', client => {
    console.log('Connected!');

    client.emit('welcome', { message: 'You are connected to WebSockets' });
});

server.list(PORT, () => console.log(`Server listening on port ${PORT}`);

But what if you want something a bit more complex? Perhaps you would like to emit an event to all connections anytime a certain route is hit in your application?

const express = require('express');
const http = require('http');
const io = require('socket.io');

const PORT = process.env.PORT || 3000;

const app = express();

app.get('/foo_endpoint', (res, res, next) => {
    const socketConnection = app.get('socket');

    socketConnection.emit('foo_endpoint_message', { message: 'Someone called /foo_endpoint' });

    res.sendStatus(200);
});

const server = http.createServer(app);
const socket = io(server);

app.set('socket', socket);

socket.on('connection', client => {
    console.log('Connected!');

    client.emit('welcome', { message: 'You are connected to WebSockets' });
});

server.list(PORT, () => console.log(`Server listening on port ${PORT}`);

Last updated