DEV Community

Duke Jones
Duke Jones

Posted on

Add WebSockets to Express

Most folks these days use the ws package.

The steps are simple. Hook into your express app, do not allow ws to create its own server, pick a path. Handle the "upgrade" event that is the protocol negotiating to go beyond simple HTTP.

import express from "express"
import cookieParser from "cookie-parser"
import * as WebSocket from 'ws';

const app = express()
app.use(express.json())
app.use(cookieParser())

// all your normal routes
app.post("/refresh-token", issueRefreshToken)
app.post("/delete-token", deleteRefreshToken)

// and now the magic
const websocketServer = new WebSocket.Server({
  noServer: true,
  path: "/echo"
})
server.on("upgrade", (request, socket, head) => {
  websocketServer.handleUpgrade(request, socket, head, (websocket) => {
    websocketServer.emit("connection", websocket, request)
  })
})

websocketServer.on('connection', (ws: WebSocket) => {

  //connection is up, let's add a simple simple event
  ws.on('message', (message: string) => {
    websocketServer.clients.forEach((client) => {
      client.send(`${message}`)
    })

    //log the received message and send it back to the client
    console.log('received: %s', message);
    ws.send(`Hello, you sent -> ${message}`);
  });

  ws.send('Hi there, I am a WebSocket server');
});

Enter fullscreen mode Exit fullscreen mode

This creates an echo server that broadcasts whatever it receives to each connected client.

To test this, wscat works well.

yarn global add wscat
Enter fullscreen mode Exit fullscreen mode

Then do this in two separate terminals:

wscat -c 'ws://localhost/echo'
Enter fullscreen mode Exit fullscreen mode

Type in one, and you should immediately see it in the other.

Top comments (0)