koa-easy-ws

raw JSON →
2.1.0 verified Sat Apr 25 auth: no javascript

Simple, composable Koa middleware for WebSocket handling. Version 2.1.0, actively maintained. Integrates the `ws` library as a peer dependency. Differentiates itself by being minimal (44 SLOC), unopinionated, and fully composable with other Koa middleware and routers. Supports custom context property names and passing options to the underlying `ws` server. Ships TypeScript types. Requires manual installation of `ws` and `koa` peer dependencies.

error TypeError: websocket is not a function
cause Forgetting to call websocket() when using app.use.
fix
Change app.use(websocket) to app.use(websocket())
error Error: Cannot find module 'ws'
cause ws peer dependency not installed.
fix
Run: npm install ws
error Error: ctx.ws is not a function
cause Using an older version where ctx.ws was the instance directly, but now it's a function.
fix
Upgrade to v2 and use await ctx.ws()
breaking In version 2.x, ctx.ws is now a function returning a Promise, not a ws instance directly.
fix Use await ctx.ws() to get the ws instance.
gotcha Must install ws and koa as peer dependencies manually.
fix Run: npm install ws koa
gotcha Middleware must be called as a function (websocket()) not just referenced.
fix Use app.use(websocket())
deprecated The default export name 'websocket' may be confused with the 'ws' library; use clear variable naming.
fix Use import easyWs from 'koa-easy-ws' or const { default: easyWs } = require('koa-easy-ws')
npm install koa-easy-ws
yarn add koa-easy-ws
pnpm add koa-easy-ws

Shows basic setup: import, middleware registration, WebSocket handling with ctx.ws, and fallback HTTP response.

import Koa from 'koa';
import websocket from 'koa-easy-ws';

const app = new Koa();
app.use(websocket());

app.use(async (ctx) => {
  if (ctx.ws) {
    const ws = await ctx.ws();
    ws.send('hello from koa-easy-ws');
  } else {
    ctx.body = 'HTTP response';
  }
});

app.listen(3000);