{"id":17981,"library":"tinyws","title":"Tiny WebSocket Middleware","description":"tinyws is a lightweight, framework-agnostic WebSocket middleware for Node.js, built upon the popular `ws` library. It enables WebSocket capabilities for HTTP servers, integrating seamlessly with frameworks like tinyhttp, Express, and Polka by exposing a `req.ws()` method. The current stable version is 1.0.0, as of April 2026. This package distinguishes itself from alternatives like `express-ws` by being actively maintained, providing first-class TypeScript support, being pure ESM, and boasting a minimal footprint (under 500B). Its primary release cadence appears to be focused on stability and maintenance rather than rapid feature additions, making it a reliable choice for adding WebSockets to modern Node.js applications.","status":"active","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/tinyhttp/tinyws","tags":["javascript","ws","express","tinyhttp","websocket","middleware","polka","http","server","typescript"],"install":[{"cmd":"npm install tinyws","lang":"bash","label":"npm"},{"cmd":"yarn add tinyws","lang":"bash","label":"yarn"},{"cmd":"pnpm add tinyws","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core WebSocket library that tinyws builds upon; required for functionality.","package":"ws","optional":false}],"imports":[{"note":"tinyws is an ESM-only package. Direct CommonJS `require` is not supported. Use dynamic import for CJS contexts.","wrong":"const tinyws = require('tinyws')","symbol":"tinyws","correct":"import { tinyws } from 'tinyws'"},{"note":"While `import type` is valid for types, `TinyWSRequest` is also exported as a value for convenience; both forms are compatible in TypeScript.","wrong":"import type { TinyWSRequest } from 'tinyws'","symbol":"TinyWSRequest","correct":"import { TinyWSRequest } from 'tinyws'"},{"note":"The quickstart example uses `@tinyhttp/app`. If using Express, substitute `express` and its `Request` type accordingly.","wrong":"import { App } from 'express'","symbol":"App","correct":"import { App, Request } from '@tinyhttp/app'"}],"quickstart":{"code":"import { App, Request } from '@tinyhttp/app';\nimport { tinyws, TinyWSRequest } from 'tinyws';\nimport { WebSocket } from 'ws'; // For type inference if needed\n\nconst app = new App<Request & TinyWSRequest>();\n\napp.use('/ws', async (req, res) => {\n  if (req.ws) {\n    const ws: WebSocket = await req.ws();\n\n    ws.on('message', (message) => {\n      console.log(`Received: ${message}`);\n      ws.send(`Echo: ${message}`);\n    });\n    ws.on('close', () => console.log('WebSocket closed.'));\n    ws.send('Hello from tinyws server!');\n  } else {\n    res.send('Hello from HTTP endpoint! This is not a WebSocket connection.');\n  }\n});\n\nconst server = app.listen(3000, () => {\n  console.log('HTTP/WebSocket server listening on port 3000');\n});\n\ntinyws(app, server, { paths: '/ws' });\n\n// To test, run:\n// node -e \"const WebSocket = require('ws'); const ws = new WebSocket('ws://localhost:3000/ws'); ws.onopen = () => ws.send('Test message'); ws.onmessage = (event) => console.log(event.data);\"","lang":"typescript","description":"This quickstart initializes a tinyhttp server with tinyws, creating a WebSocket endpoint at `/ws` that echoes messages back to the client. It demonstrates how to access the WebSocket instance via `req.ws()` and handle basic messaging."},"warnings":[{"fix":"Ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json`). For mixed CJS/ESM projects, use `import()` within an `async` function: `const { tinyws } = await import('tinyws');`","message":"tinyws is a pure ESM package. Applications that are strictly CommonJS (CJS) will need to convert to ESM or use dynamic `import()` for tinyws to function correctly. Direct `require()` calls will result in an error.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Run `npm install ws` or `pnpm i ws` in your project directory.","message":"It is crucial to install the `ws` package alongside `tinyws`, as `ws` is a peer dependency and not bundled. Forgetting `ws` will lead to runtime errors when tinyws attempts to use it.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Follow the pattern `const server = app.listen(PORT); tinyws(app, server);` ensuring both `app` and the raw `http.Server` instance are provided.","message":"When integrating `tinyws` with an HTTP server, ensure the `tinyws` initialization function is called *after* the HTTP server is created and passed the `app` instance and the `server` object. Calling it too early or with incorrect arguments will prevent WebSocket upgrades from functioning.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always use `if (req.ws) { const ws = await req.ws(); /* ... */ }` within your route handler to properly establish and interact with the WebSocket.","message":"Unlike some other middleware, `tinyws` exposes the WebSocket functionality via a `req.ws()` *function* that returns a Promise for the WebSocket instance. Developers must `await` this call and check for `req.ws`'s existence to correctly handle WebSocket connections.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Run `npm install ws` or `pnpm i ws` to add the required WebSocket library.","cause":"The `ws` package, a peer dependency, has not been installed.","error":"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'ws' imported from tinyws"},{"fix":"Ensure `tinyws(app, server, { paths: '/your-ws-path' });` is called after your HTTP server is created, and that the client is connecting to one of the specified `paths`.","cause":"The `tinyws` middleware was not correctly initialized with your application and HTTP server, or the request path does not match a configured WebSocket path.","error":"TypeError: Cannot read properties of undefined (reading 'ws')"},{"fix":"Ensure your `Request` type is augmented with `TinyWSRequest` (e.g., `App<Request & TinyWSRequest>`) and that you `await req.ws()` to get the WebSocket instance.","cause":"The `tinyws` middleware might be applied but `req.ws` is not correctly typed or the `req.ws` property is not being awaited.","error":"TypeError: req.ws is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}