npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rudderjs/sync

v1.0.0

Published

Real-time collaborative document sync engine for RudderJS — Yjs CRDT over WebSocket, with a Lexical editor adapter under a subpath export.

Downloads

445

Readme

@rudderjs/sync

Real-time collaborative document sync engine for RudderJS — Yjs CRDT over WebSocket. Editor-agnostic core with adapters under subpath exports.

Works alongside @rudderjs/broadcast — the sync engine uses the same port and process, no separate server needed.

Installation

pnpm add @rudderjs/sync

Setup

SyncProvider is auto-discovered. Install the package, run pnpm rudder providers:discover, and configure via config/sync.ts:

// config/sync.ts
import type { SyncConfig } from '@rudderjs/sync'

export default {
  path: '/ws-sync',
} satisfies SyncConfig
// bootstrap/providers.ts
import { defaultProviders } from '@rudderjs/core'

export default [...(await defaultProviders())]
// bootstrap/app.ts (optional — only if you broadcast over channels too)
.withRouting({
  channels: () => import('../routes/channels.ts'),
})

Both /ws (broadcast) and /ws-sync (sync) share the same port — no proxy, no extra process. Register BroadcastingProvider before SyncProvider if you use both — defaultProviders() orders them correctly out of the box.

To opt out of auto-discovery, import SyncProvider from @rudderjs/sync and list it explicitly.


Editor Adapters

Yjs is editor-agnostic; the core package handles document sync. For server-side mutations against editor-specific document shapes, use the relevant adapter under a subpath import:

| Adapter | Subpath | Status | |---|---|---| | Lexical | @rudderjs/sync/lexical | Available | | Tiptap | planned | Coming in a future release |

import { Sync }                    from '@rudderjs/sync'
import { editBlock, insertBlock }  from '@rudderjs/sync/lexical'

const doc = Sync.document('panel:articles:42:richcontent:body')
insertBlock(doc, 'callToAction', { title: 'Subscribe' })
editBlock(doc, 'callToAction', 0, 'buttonText', 'Learn More')

Persistence Drivers

All driver selection happens in config/sync.ts — the SyncProvider reads it on boot.

Memory (default)

Zero config. Documents live in RAM and reset on server restart. Good for development and ephemeral sessions.

// config/sync.ts
export default {} satisfies SyncConfig

Prisma

Documents persist in your database. Add a model to your Prisma schema:

model SyncDocument {
  id        String   @id @default(cuid())
  docName   String
  update    Bytes
  createdAt DateTime @default(now())

  @@index([docName])
}

Then wire the adapter:

// config/sync.ts
import { syncPrisma } from '@rudderjs/sync'

export default {
  persistence: syncPrisma({ model: 'syncDocument' }),
} satisfies SyncConfig

Redis

Documents cached in Redis. Supports multiple server instances behind a load balancer.

pnpm add ioredis
// config/sync.ts
import { syncRedis } from '@rudderjs/sync'

export default {
  persistence: syncRedis({ url: process.env.REDIS_URL }),
} satisfies SyncConfig

Auth

Protect documents with an onAuth callback. Return true to allow, false to deny.

// config/sync.ts
export default {
  onAuth: async (req, docName) => {
    const token = req.token ?? req.headers['authorization']
    return verifyToken(token)
  },
} satisfies SyncConfig

The req object contains:

  • req.headers — upgrade request headers (cookies, Authorization, etc.)
  • req.url — full upgrade URL
  • req.token — token passed by the client as a query parameter

onChange

Called (with the raw Yjs update) whenever a document changes. Useful for indexing, webhooks, or audit logs.

// config/sync.ts
export default {
  onChange: async (docName, update) => {
    console.log(`Document "${docName}" updated`)
    await searchIndex.update(docName, update)
  },
} satisfies SyncConfig

Custom Path

// config/sync.ts
export default { path: '/ws-collab' } satisfies SyncConfig

Client

The client uses standard Yjs — no custom library needed. Install yjs and y-websocket:

pnpm add yjs y-websocket
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'

const doc      = new Y.Doc()
const provider = new WebsocketProvider('ws://localhost:3000/ws-sync', 'my-document', doc)

provider.on('status', ({ status }) => {
  console.log(status) // 'connecting' | 'connected' | 'disconnected'
})

Offline support (browser)

Pair with y-indexeddb for offline-first editing — documents load from IndexedDB instantly and sync when the connection is restored:

pnpm add y-indexeddb
import { IndexeddbPersistence } from 'y-indexeddb'

const local = new IndexeddbPersistence('my-document', doc)
local.on('synced', () => console.log('Loaded from local storage'))

Awareness (presence & cursors)

Track who is online and share cursor positions:

provider.awareness.setLocalStateField('user', {
  name:  'Alice',
  color: '#f5a623',
})

provider.awareness.on('change', () => {
  const users = [...provider.awareness.getStates().values()]
  renderCursors(users)
})

React + Valtio

For a nicer state management experience in React, pair with valtio-yjs:

pnpm add valtio valtio-yjs
import { proxy, useSnapshot } from 'valtio'
import { bind }               from 'valtio-yjs'

const ymap = doc.getMap('state')
const state = proxy({ title: '', content: '' })
bind(state, ymap)

function Editor() {
  const snap = useSnapshot(state)
  return (
    <input
      value={snap.title}
      onChange={e => { state.title = e.target.value }}
    />
  )
}

Rudder Commands

pnpm rudder sync:docs          # List active documents and client counts
pnpm rudder sync:clear <doc>   # Clear a document from persistence
pnpm rudder sync:inspect <doc> # Inspect the Y.Doc tree structure

Document Names

The document name is extracted from the WebSocket URL path:

ws://localhost:3000/ws-sync/my-document  →  docName = "my-document"
ws://localhost:3000/ws-sync/report-2026  →  docName = "report-2026"

Multiple clients connecting to the same document name automatically share state.


Persistence Drivers Comparison

| Driver | Persistence | Scales | Use case | |---|---|---|---| | MemoryPersistence (default) | Resets on restart | Single instance | Dev, demos, ephemeral | | syncPrisma() | Database | Single instance | Most production apps | | syncRedis() | Redis | Multi-instance | High-traffic, horizontal scale |

For very large scale (millions of users), run yhub as a separate service — it's y-websocket compatible so clients work without any changes.


Custom Persistence Adapter

Implement the SyncPersistence interface to use any storage backend:

import type { SyncPersistence } from '@rudderjs/sync'
import * as Y from 'yjs'

class MyAdapter implements SyncPersistence {
  async getYDoc(docName: string): Promise<Y.Doc> { ... }
  async storeUpdate(docName: string, update: Uint8Array): Promise<void> { ... }
  async getStateVector(docName: string): Promise<Uint8Array> { ... }
  async getDiff(docName: string, stateVector: Uint8Array): Promise<Uint8Array> { ... }
  async clearDocument(docName: string): Promise<void> { ... }
  async destroy(): Promise<void> { ... }
}

// config/sync.ts
export default { persistence: new MyAdapter() } satisfies SyncConfig

How It Works

  1. Client connects via WebSocket to /ws-sync/document-name
  2. Server sends its state vector (what it knows)
  3. Client replies with a diff (what the server is missing)
  4. Client receives a diff back (what the client is missing)
  5. Both sides are now in sync — subsequent updates broadcast to all connected clients
  6. Updates are persisted via the configured adapter

This is the standard Yjs sync protocol — compatible with any y-websocket client.


Migration from @rudderjs/live

This package was previously named @rudderjs/live. Renamed in 0.1.0 to better reflect its purpose (sync engine, not just "live updates"). Lexical-specific helpers moved to @rudderjs/sync/lexical.

| Before | After | |---|---| | @rudderjs/live | @rudderjs/sync | | Live facade | Sync facade | | LiveProvider | SyncProvider | | LiveConfig | SyncConfig | | LivePersistence | SyncPersistence | | livePrisma, liveRedis | syncPrisma, syncRedis | | LIVE_UPGRADE_KEY | SYNC_UPGRADE_KEY | | /ws-live | /ws-sync | | config/live.ts | config/sync.ts | | 'liveDocument' (Prisma model default) | 'syncDocument' | | 'rudderjs:live:' (Redis prefix) | 'rudderjs:sync:' | | pnpm rudder live:docs | pnpm rudder sync:docs | | Live.editBlock, Live.insertBlock, etc. | Imported from @rudderjs/sync/lexical |