Universal WebSocket Client

raw JSON →
1.0.3 verified Thu Apr 23 auth: no javascript abandoned

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.

error require is not defined
cause Attempting to run CommonJS `require()` in a browser or in a Node.js ESM module without a transpiler or bundler to convert it.
fix
For browser usage, ensure your code is bundled with Browserify, Webpack, or a similar tool. For Node.js ESM modules, use 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)
cause The underlying `ws` dependency for Node.js environments is either missing or not correctly resolved by the `universal-websocket-client` package's internal logic.
fix
Ensure the 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)
cause Incorrect import syntax or bundler configuration when trying to use a CJS-only package with an ESM `import` statement, where the bundler incorrectly handles the module's exports.
fix
Try adjusting your import statement in TypeScript: 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.
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.
fix For new projects, consider using actively maintained alternatives. For Node.js, the `ws` package is a robust choice. For universal/isomorphic applications, consider modern solutions that offer native ESM support, TypeScript definitions, and active community backing like `@ws-kit/client` or directly managing environment-specific WebSocket implementations.
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.
fix For browser environments, your code must be bundled with a tool like Webpack or Browserify. For Node.js ESM projects, you'll need to configure your bundler to handle CJS modules or use Node.js's `createRequire` utility for explicit CJS imports.
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.
fix Manually create a `universal-websocket-client.d.ts` file in your project with basic type declarations, for example, `declare module 'universal-websocket-client' { export = WebSocket; }` and extend the global `WebSocket` interface or provide a custom type definition.
npm install universal-websocket-client
yarn add universal-websocket-client
pnpm add universal-websocket-client

Demonstrates how to establish a WebSocket connection and handle messages using `universal-websocket-client`. Includes a minimal Node.js echo server for local testing and illustrates client usage for both Node.js and browser environments.

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);
}