deepstream.io JavaScript Client

raw JSON →
2.3.4 verified Thu Apr 23 auth: no javascript

The `deepstream.io-client-js` library is the official JavaScript client for connecting to a deepstream.io server, enabling real-time data synchronization, remote procedure calls (RPCs), and publish/subscribe messaging patterns. The current major stable version, `4.0.0`, brought significant advancements over previous versions. This includes a new binary protocol for improved efficiency, full TypeScript declaration files for enhanced developer experience, and a comprehensive shift to promise-based APIs, leveraging `async/await` for asynchronous operations. A key differentiator is its robust offline support, allowing data to be stored client-side using IndexedDB and synchronized upon reconnection. While a precise release cadence isn't explicitly defined, the jump to `v4.0.0` indicates active and substantial development. It's designed for high-performance, real-time applications, offering an opinionated, stateful data synchronization model that distinguishes it from simpler WebSocket libraries or REST-based solutions.

error Error: CONNECTION_ERROR - Cannot connect to deepstream
cause The deepstream.io server is not running, is inaccessible, or the client is attempting to connect to an incorrect WebSocket URL (e.g., wrong port, HTTP instead of WS/WSS).
fix
Verify that your deepstream.io server is running and reachable. Ensure the deepstream client factory is initialized with the correct WebSocket endpoint (e.g., ws://localhost:6020 or wss://your.domain:6020). Check firewall rules if connecting remotely.
error TypeError: deepstream(...) is not a function
cause This error often occurs in CommonJS environments if the `deepstream` client factory function is incorrectly imported or treated as an object with named exports instead of a direct callable function.
fix
For CommonJS, use const deepstream = require('deepstream.io-client-js');. For ES Modules, ensure you follow the pattern shown in the documentation: import * as deepstream from 'deepstream.io-client-js'; then use deepstream(...).
error TS2307: Cannot find module 'deepstream.io-client-js' or its corresponding type declarations.
cause The TypeScript compiler is unable to locate the type definition files for the package. This can happen if the package is not installed, `tsconfig.json` is misconfigured, or the explicit `typeRoots` path mentioned in the README is incorrect.
fix
First, confirm deepstream.io-client-js is installed in your node_modules. Review your tsconfig.json for proper compilerOptions and ensure any explicit typeRoots or include paths are correct and point to the bundled type definitions (src/client.d.ts). Modern TypeScript setups often resolve types automatically if the package is installed.
breaking Version 4.0.0 introduced a new, incompatible binary protocol. Upgrading the client to `v4.0.0` or later requires the deepstream.io server to also be running a compatible version (e.g., `v4.x` or newer) to establish a connection.
fix Ensure your deepstream.io server is updated to a version compatible with `deepstream.io-client-js` v4.0.0+.
breaking With `v4.0.0`, nearly all asynchronous APIs (e.g., `login`, `record.get`, `event.emit`) were refactored to return Promises, aligning with modern JavaScript `async/await` patterns. Callback-based APIs from previous versions are largely deprecated or removed.
fix Refactor existing asynchronous code to use `.then()/.catch()` or `async/await` syntax for handling responses and errors. Consult the `v4.0.0` documentation for updated API signatures.
gotcha The configuration structure for offline support, including `offlineEnabled`, `saveUpdatesOffline`, and `indexdb` options, was introduced or significantly revised in `v4.0.0`. Older client configurations for offline features will not be compatible.
fix Review and update your client initialization configuration object, especially the `offlineEnabled` and `indexdb` properties, to match the `v4.0.0` specification for offline capabilities.
gotcha The README suggests an explicit `typeRoots` entry in `tsconfig.json` (`"./node_modules/deepstream.io-client.js/src/client.d.ts"`) for TypeScript types. While functional, this approach is less common in modern TypeScript setups, which typically discover types automatically. This explicit path can sometimes conflict with other type resolution strategies.
fix Ensure `tsconfig.json` is correctly configured. If experiencing type resolution issues, verify the specified `typeRoots` path is accurate. In many cases, types may be automatically discovered without this explicit `typeRoots` entry, depending on your `compilerOptions.moduleResolution`.
npm install deepstream.io-client-js
yarn add deepstream.io-client-js
pnpm add deepstream.io-client-js

This quickstart demonstrates how to connect to a deepstream.io server, handle connection state changes, perform a promise-based login, subscribe to and update a data record, and emit a real-time event.

import * as deepstream from 'deepstream.io-client-js';

const DEEPSTREAM_URL = process.env.DEEPSTREAM_URL ?? 'ws://localhost:6020'; // Use wss:// for secure connections

const client = deepstream(DEEPSTREAM_URL);

client.on('connectionStateChanged', (connectionState) => {
  console.log(`Deepstream connection state: ${connectionState}`);
  if (connectionState === 'CLOSED' || connectionState === 'ERROR') {
    console.error('Deepstream connection issue. Please check server status and URL.');
  }
});

client.login({ username: 'testUser', password: 'password123' })
  .then(() => {
    console.log('Login successful!');

    // Example: Working with a record
    const userRecord = client.record.get('users/john-doe');
    userRecord.subscribe((data) => {
      console.log('User record updated:', data);
    });
    userRecord.set({ name: 'John Doe', email: 'john.doe@example.com', lastUpdated: Date.now() });

    // Example: Publishing an event
    client.event.emit('user-activity', { userId: 'john-doe', action: 'loggedIn' });

  })
  .catch((error) => {
    console.error('Login failed:', error.message);
  });

// Keep the Node.js process alive for events/records to sync
// Not necessary in a browser environment
setInterval(() => {}, 1000 * 60);