express-ws alternative in TypeScript

Viewed 5019

I have been searching for a few days now but still haven’t found any alternative or help writing a TypeScript Declaration for it as I also tried that.

https://www.npmjs.com/package/express-ws

Important is that it works with any other route in express. Authentication, Roles and Path Parameters.

3 Answers

Typings for express-ws have now been created.

The tests show how to use it:

import expressWs from 'express-ws';
const { app, getWss, applyTo } = expressWs(express());

Or:

const app = expressWs(express()).app;

Then for example when declaring routes rather than writing:

const myRoutes = function(app: Express) {...}

You need to specify the express-ws type:

import expressWs from 'express-ws';
const myRoutes = function(app: expressWs.Application) {...}

Thanks Derek Hill and Normunds Kalnberzins

Works with routers is better

First import express-ws

import expressWs from 'express-ws';

To use the ws method, you need to strengthen express (I understand it this way)

const { app, getWss, applyTo } = expressWs(express());

after that express.Router contains the ws method, but the type of the typescript is wrong, you only need to convert the type.

const router = express.Router() as expressWs.Router;

Define the routing logic

router.ws('/echo', (ws, req) => {
    ws.on('message', (msg: String) => {
        ws.send(msg);
    });
});

Finally add router to the express app

app.use("/ws-stuff", router);
Related