Skip to content

Instantly share code, notes, and snippets.

@porsager
Last active September 23, 2023 05:14
Show Gist options
  • Save porsager/eb754973e9e1c43842ca9c04001236d8 to your computer and use it in GitHub Desktop.
Save porsager/eb754973e9e1c43842ca9c04001236d8 to your computer and use it in GitHub Desktop.
A websocket middleware for express

A websocket middleware for express

A convenient way to expose a websocket connections in route handles.

Usage

const express = require('express')
    , ws = require('./ws')

const app = express()

app.get('/', (req, res) => 
  req.ws
    ? res.ws(socket => /* do something with the socket */ )
    : res.send('Hello you non websocket')
)

app.listen(PORT)

server.on('upgrade', ws(app))
const uws = require('uws')
, http = require('http')
const wss = new uws.Server({ noServer: true })
module.exports = app => (req, socket, head) => {
const res = new http.ServerResponse(req)
res.assignSocket(socket)
res.on('finish', () => res.socket.destroy())
req.ws = true
res.ws = fn => wss.handleUpgrade(req, socket, head, fn)
app(req, res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment