DEV Community

Duke Jones
Duke Jones

Posted on

5 1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay