tinyws is a WebSocket middleware for Node.js based on ws, inspired by koa-easy-ws.
Check the chat example out to get familiar with tinyws.
Features
- Small size (498B)
- Easy to use (only
req.ws
and nothing else) - Framework-agnostic (works with tinyhttp, express etc)
- Written in TypeScript
- Pure ESM
express-ws?
Why notbecause express-ws is...
- Abandoned since 2018
💀 - Doesn't come with types out of the box (have to install
@types/express-ws
) - Not compatible with tinyhttp and polka
- Buggy as hell
- Doesn't have tests
Install
npm i ws tinyws
Example
import { App, Request } from '@tinyhttp/app'
import { tinyws, TinyWSRequest } from 'tinyws'
const app = new App<any, Request & TinyWSRequest>()
app.use(tinyws())
app.use('/ws', async (req, res) => {
if (req.ws) {
const ws = await req.ws()
return ws.send('hello there')
} else {
res.send('Hello from HTTP!')
}
})
app.listen(3000)
const express = require('express')
const { tinyws } = require('tinyws')
const app = express()
app.use(tinyws())
app.use('/ws', async (req, res) => {
if (req.ws) {
const ws = await req.ws()
ws
.on('message', function (msg) {
console.debug('ws receive: %j', msg)
ws.send('Recceive :' + msg)
})
.on('close', () => {
console.debug('ws close')
})
return ws.send('hello there')
} else {
res.send('Hello from HTTP!')
}
})
app.listen(3000)