{"id":17766,"library":"koa-websocket","title":"Koa WebSocket Middleware","description":"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.","status":"active","version":"7.0.0","language":"javascript","source_language":"en","source_url":"git://github.com/kudos/koa-websocket","tags":["javascript","koa","websockets","ws","sockets","routes"],"install":[{"cmd":"npm install koa-websocket","lang":"bash","label":"npm"},{"cmd":"yarn add koa-websocket","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-websocket","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core WebSocket server implementation that koa-websocket wraps and depends on for all WebSocket protocol handling.","package":"ws","optional":false}],"imports":[{"note":"The `websockify` function is the default export from `koa-websocket`. It extends a Koa application instance to add WebSocket capabilities. While CommonJS `require` is common in older Koa projects and examples, ESM `import` is recommended for new projects and aligns with modern Node.js practices.","wrong":"import { websockify } from 'koa-websocket'; // This is not a named export.\nconst websockify = require('koa-websocket'); // Functional CommonJS syntax, but ESM is preferred in modern Koa projects.","symbol":"websockify","correct":"import websockify from 'koa-websocket';"},{"note":"Required to create the base Koa application instance that `koa-websocket` will extend.","wrong":"const Koa = require('koa');","symbol":"Koa","correct":"import Koa from 'koa';"},{"note":"Commonly used alongside `koa-websocket` for routing WebSocket connections, mimicking the `koa-route` pattern for HTTP routes. This is a separate, optional package.","wrong":"const route = require('koa-route');","symbol":"route","correct":"import route from 'koa-route';"}],"quickstart":{"code":"import Koa from 'koa';\nimport route from 'koa-route';\nimport websockify from 'koa-websocket';\n\n// Create a new Koa application and extend it with WebSocket capabilities\nconst app = websockify(new Koa());\n\n// Basic HTTP middleware (optional, but shows coexistence)\napp.use(async (ctx, next) => {\n  console.log(`HTTP Request: ${ctx.method} ${ctx.path}`);\n  await next();\n});\n\n// Global WebSocket middleware for all connections\napp.ws.use(async (ctx, next) => {\n  console.log(`New WebSocket connection established for path: ${ctx.path}`);\n  // You can perform authentication or other setup here\n  await next(ctx); // Pass context to the next WebSocket middleware or route\n});\n\n// WebSocket route handler using koa-route\napp.ws.use(route.all('/chat/:id', (ctx) => {\n  const roomId = ctx.params.id;\n  console.log(`Client connected to chat room: ${roomId}`);\n\n  // Send a welcome message to the newly connected client\n  ctx.websocket.send(`Welcome to chat room ${roomId}!`);\n\n  // Listen for messages from this client\n  ctx.websocket.on('message', (message) => {\n    console.log(`Message from client in room ${roomId}: ${message}`);\n    // Echo the message back to the sender\n    ctx.websocket.send(`Echo (${roomId}): ${message}`);\n  });\n\n  // Handle client disconnection\n  ctx.websocket.on('close', () => {\n    console.log(`Client disconnected from chat room: ${roomId}`);\n  });\n\n  // Handle WebSocket errors\n  ctx.websocket.on('error', (err) => {\n    console.error(`WebSocket error in room ${roomId}:`, err.message);\n  });\n}));\n\n// Start the server on an available port, defaulting to 3000\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server listening on http://localhost:${PORT} and ws://localhost:${PORT}`);\n  console.log('Try connecting with a WebSocket client to ws://localhost:3000/chat/general');\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"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`.","message":"Version 7.0.0 upgraded the underlying `ws` library to version 8.5.0. This may introduce breaking changes or behavioral shifts from `ws` that could affect your existing WebSocket client or server logic. Always consult the `websockets/ws` release notes.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Upgrade your Node.js runtime environment to version 8.x or newer. For current releases of `koa-websocket`, Node.js 12+ is generally recommended.","message":"With `koa-websocket` v6.0.0, the `ws` dependency was upgraded to 7.0.1, which dropped support for Node.js 6.x. Running on older Node.js versions will lead to errors.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"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.","message":"`koa-websocket` versions 4.0.0 and above are built for Koa v2. If you are using Koa v1, you must explicitly install `koa-websocket@2` to maintain compatibility.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure all functions intended to handle WebSocket connections or messages are passed to `app.ws.use`.","message":"WebSocket middleware must be registered using `app.ws.use(...)` and not `app.use(...)`. The `app.use` method is for standard HTTP middleware, while `app.ws.use` is specific to WebSocket connections.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"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.","message":"Within `app.ws.use` middleware or route handlers, the Koa context (`ctx`) is augmented with the active WebSocket connection at `ctx.websocket`. You must use `ctx.websocket` to interact with the client.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Pass a valid `httpsOptions` object (containing `key`, `cert`, etc.) from your SSL certificate setup as `websockify(new Koa(), wsOptions, httpsOptions)`.","message":"To enable `wss://` (secure WebSockets), you must provide `httpsOptions` as the third argument to the `websockify` function. Without these options, only `ws://` connections will be supported.","severity":"gotcha","affected_versions":">=4.1.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure your Koa app is initialized by wrapping it: `const app = websockify(new Koa());`","cause":"The Koa application instance was not correctly wrapped by the `websockify` function from `koa-websocket`.","error":"TypeError: app.ws.use is not a function"},{"fix":"Install Koa: `npm install koa`.","cause":"The `koa` package, which is a peer dependency in practice, has not been installed in your project.","error":"Error: Cannot find module 'koa'"},{"fix":"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.","cause":"The WebSocket client is trying to connect to a path for which no `app.ws.use` route handler is configured or the path is incorrect.","error":"WebSocket connection to 'ws://localhost:3000/some-path' failed: Error during WebSocket handshake: Unexpected response code: 404"},{"fix":"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'`).","cause":"When using `wss://` with a self-signed or otherwise untrusted SSL certificate, clients will typically reject the connection unless explicitly configured to trust the certificate.","error":"Error: self-signed certificate in certificate chain (for wss:// connections)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}