socket.js middleware code example

Example: socket io middleware

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

// Setup server and socket
const port = 3000;
const app = express();
const server = app.listen(port, console.log(`Listening on port ${port}...`));
const io = socketio(server);

// Calls the middleware on every new connection
io.use((socket, next) => {
  if (/* should connect socket */) {
    next();
  } else {
    next(new Error('Connection failed.'));
  }
});

io.on('connection', (socket) => {
  // Calls the middleware on every event
  socket.use((packet, next) => {
    const event = packet[0];
    const data = packet.slice(1);
    
    if (/* should run event */) {
      next();
    } else {
      next(new Error('Failed to emit the event.'));
    }
  });

  // Example event
  socket.on('msg', (data) => {
    socket.broadcast.emit('msg', data.msg);
  });
});