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)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!