Universal WebSocket Client
raw JSON →The `universal-websocket-client` package provides a unified API for WebSocket communication across both browser and Node.js environments. It achieves this by utilizing the native `WebSocket` API in browsers and integrating with the `ws` package for Node.js, allowing developers to write isomorphic applications with a single WebSocket client interface. Currently at version 1.0.3, the package appears to be in an abandoned state, with its last update occurring approximately seven years ago, indicating no active development or maintenance. Its primary differentiator was simplifying cross-environment WebSocket usage before native ESM and modern bundler configurations became prevalent, specifically by avoiding the inclusion of Node.js-specific WebSocket implementations in browser builds.
Common errors
error require is not defined ↓
import { createRequire } from 'module'; const require = createRequire(import.meta.url); const WebSocket = require('universal-websocket-client'); or switch the file to CommonJS (.cjs extension or "type": "commonjs" in package.json). error WebSocket is not defined (in Node.js) ↓
ws package is installed as a direct dependency of your project: npm install ws. If the issue persists, verify the version of Node.js as modern Node.js versions may have native WebSocket client support. error TypeError: universal_websocket_client__WEBPACK_IMPORTED_MODULE_0__ is not a constructor (or similar bundler error with ESM import) ↓
import WebSocket = require('universal-websocket-client');. For JavaScript, ensure your bundler is configured to correctly handle CommonJS interop, potentially using import * as WebSocket from 'universal-websocket-client'; if the module exports are bundled as a namespace, or check bundler-specific plugins/options for CJS compatibility. Warnings
deprecated The `universal-websocket-client` package appears to be abandoned, with its last publish date being approximately seven years ago. This indicates a lack of active development, maintenance, and security updates. ↓
gotcha This package is designed for CommonJS (`require`) and predates native ESM support in Node.js and browsers. Using it in modern ESM-only environments without proper bundler configuration will lead to import errors. ↓
gotcha No official TypeScript definitions are provided by the package. Developers using TypeScript will need to create their own declaration files (`.d.ts`) or search for community-maintained `@types` packages, which are unlikely to exist for an abandoned library. ↓
Install
npm install universal-websocket-client yarn add universal-websocket-client pnpm add universal-websocket-client Imports
- WebSocket wrong
import WebSocket from 'universal-websocket-client';correctconst WebSocket = require('universal-websocket-client');
Quickstart
const WebSocket = require('universal-websocket-client');
// Minimal Node.js echo server for demonstration purposes
let wss;
let server;
if (typeof window === 'undefined') { // Only set up server in Node.js environment
const http = require('http');
const { WebSocketServer } = require('ws');
server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('WebSocket server running for demo\n');
});
wss = new WebSocketServer({ server });
wss.on('connection', ws => {
console.log('[Server] Client connected');
ws.on('message', message => {
console.log(`[Server] Received: ${message}`);
ws.send(`Echo: ${message}`);
});
ws.on('close', () => console.log('[Server] Client disconnected'));
});
server.listen(8080, () => {
console.log('[Server] Echo WebSocket server listening on port 8080');
startClient('ws://localhost:8080');
});
} else {
// For browser, connect to a public echo server or your own backend
startClient('wss://echo.websocket.events');
}
function startClient(url) {
console.log(`[Client] Attempting to connect to WebSocket at ${url}`);
const ws = new WebSocket(url);
ws.onopen = () => {
console.log('[Client] WebSocket connection opened!');
ws.send('Hello from universal-websocket-client!');
};
ws.onmessage = (event) => {
console.log(`[Client] Received: ${event.data}`);
};
ws.onerror = (error) => {
console.error('[Client] WebSocket error:', error);
};
ws.onclose = (event) => {
if (event.wasClean) {
console.log(`[Client] WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`);
} else {
console.warn('[Client] WebSocket connection abruptly disconnected!');
}
// Gracefully shut down the demo server if in Node.js
if (wss && server) {
wss.close(() => {
server.close(() => {
console.log('[Server] Server gracefully shut down.');
});
});
}
};
// Send a message after 2 seconds, then close after 4 seconds
setTimeout(() => ws.send('Another message!'), 2000);
setTimeout(() => ws.close(1000, 'Demo complete'), 4000);
}