koa-websocket is a lightweight wrapper designed to integrate WebSocket functionality into Koa applications, providing a middleware handler that is compatible with `koa-route`. It leverages the popular `ws` library for its core WebSocket implementation. The package is currently at version 7.0.0 and has seen regular updates, including dependency upgrades to address security concerns and support newer Node.js versions. Key features include support for both `ws://` and `wss://` protocols, the ability to pass custom WebSocket server options, and seamless integration with Koa's middleware pattern via `app.ws.use`. It differentiates itself by offering a `koa-route`-like approach to WebSocket routing within the Koa ecosystem, simplifying the handling of WebSocket connections and messages alongside traditional HTTP routes, providing a structured way to build WebSocket-enabled Koa applications.
npm install koa-websocketVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up a Koa application that handles both HTTP and WebSocket requests using `koa-websocket` and `koa-route`. It includes global WebSocket middleware and a specific route for `/chat/:id` to manage and interact with client messages.
Review the official `websockets/ws` GitHub releases for version 8.x for specific breaking changes. Thoroughly test your application, including client-side WebSocket interactions, after upgrading `koa-websocket`.
Upgrade your Node.js runtime environment to version 8.x or newer. For current releases of `koa-websocket`, Node.js 12+ is generally recommended.
For Koa v1 projects, install `npm install koa-websocket@2`. For Koa v2 and newer, use `npm install koa-websocket` to get the latest compatible version.
Ensure all functions intended to handle WebSocket connections or messages are passed to `app.ws.use`.
To send data, use `ctx.websocket.send()`. To listen for client messages or connection events, use `ctx.websocket.on('message', ...)` or `ctx.websocket.on('close', ...)`, etc.Pass a valid `httpsOptions` object (containing `key`, `cert`, etc.) from your SSL certificate setup as `websockify(new Koa(), wsOptions, httpsOptions)`.
Ensure your Koa app is initialized by wrapping it: `const app = websockify(new Koa());`
Install Koa: `npm install koa`.
Verify that your client's WebSocket URL matches an `app.ws.use(route.all('/your-path', ...))` handler defined in your server-side code. Check for typos in paths and ensure the handler is correctly registered.For production, use a trusted SSL certificate from a Certificate Authority (e.g., Let's Encrypt). For development, configure your client to ignore self-signed certificates if applicable (e.g., for Node.js clients, `process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'`).