Guide
Best npm Packages for Real-Time Features 2026



Socket.io, PartyKit, Yjs, and Ably compared for adding real-time features to JavaScript apps in 2026. WebSockets, multiplayer, CRDT-based collaboration, and.
Contents
Contents
TL;DR
Use Socket.io for chat or notifications on a Node.js server, PartyServer for custom rooms on your Cloudflare account, and Ably for managed pub/sub. For a collaborative editor, add Yjs and choose a provider to sync the document. Managed PartyKit has shut down. Use PartyServer with Wrangler for new Cloudflare rooms.
Key Takeaways
- Socket.io provides rooms, namespaces, reconnects, and a Redis adapter for multiple Node.js instances.
- PartyServer puts each room in a Cloudflare Durable Object. Your Worker handles routing and writes any history you want to keep.
- Yjs merges concurrent document edits. Use a provider such as
y-websocketory-partyserverto sync updates. - Ably runs the messaging infrastructure and provides channels and presence.
The Real-Time Landscape in 2026
Adding real-time features to a web application used to mean one of two things: polling an endpoint every few seconds (simple but wasteful) or setting up a WebSocket server (correct but operationally complex). WebSocket infrastructure introduces stateful server connections, which breaks the stateless deployment model that made serverless and edge computing so appealing.
Cloudflare Durable Objects let a Worker route connections to a stateful room. With PartyServer, your team still owns the Worker deployment and its room logic. With Ably, your application publishes to a managed messaging service.
At the same time, Socket.io remains the most practical solution for teams already running Node.js servers who want to add WebSocket functionality without introducing external dependencies. And Yjs has become the standard library for collaborative editing regardless of which transport you use underneath.
Understanding which layer of the stack each tool addresses is the key to combining them correctly.
Socket.io for Node.js WebSocket Rooms
Choose Socket.io when your Node.js app needs named rooms and event delivery over one connection. A chat room, a notification stream, and a live dashboard can use the same server with different event handlers.
Socket.io's core abstractions — rooms, namespaces, and automatic reconnection — handle the most common patterns in real-time applications. A room is a named channel that connections can join and leave. A namespace is a logical partition of the Socket.io server (like separate paths for different parts of an application). Automatic reconnection means clients re-establish their connection without any application code if the server restarts or the network drops.
npm install socket.io socket.io-client
// server/socket.ts — Socket.io with Express
import { Server } from 'socket.io';
import { createServer } from 'http';
import { app } from './app';
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: process.env.FRONTEND_URL,
credentials: true,
},
transports: ['websocket', 'polling'], // Polling as fallback
});
// Middleware for authentication
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
const user = await verifyToken(token);
if (!user) return next(new Error('Unauthorized'));
socket.data.userId = user.id;
socket.data.userName = user.name;
next();
});
io.on('connection', (socket) => {
const { userId, userName } = socket.data;
// Automatically join user's private room
socket.join(`user:${userId}`);
socket.on('join-channel', (channelId: string) => {
socket.join(`channel:${channelId}`);
io.to(`channel:${channelId}`).emit('user-joined', { userId, userName });
});
socket.on('leave-channel', (channelId: string) => {
socket.leave(`channel:${channelId}`);
io.to(`channel:${channelId}`).emit('user-left', { userId });
});
socket.on('send-message', async (data: { channelId: string; content: string }) => {
// Persist to database first
const message = await db.message.create({
data: {
channelId: data.channelId,
senderId: userId,
content: data.content,
},
include: { sender: { select: { id: true, name: true } } },
});
// Broadcast to everyone in the channel
io.to(`channel:${data.channelId}`).emit('new-message', message);
});
socket.on('typing', (channelId: string) => {
// Broadcast to everyone except sender
socket.to(`channel:${channelId}`).emit('user-typing', { userId, userName });
});
socket.on('disconnect', () => {
// Notify relevant rooms
io.emit('user-offline', { userId });
});
});
httpServer.listen(3001);
// React client with Socket.io
import { io, Socket } from 'socket.io-client';
import { useEffect, useRef, useState } from 'react';
function useChatSocket(channelId: string, token: string) {
const socketRef = useRef<Socket | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
const [typingUsers, setTypingUsers] = useState<string[]>([]);
useEffect(() => {
const socket = io(process.env.NEXT_PUBLIC_WS_URL!, {
auth: { token },
transports: ['websocket'],
});
socket.on('connect', () => {
socket.emit('join-channel', channelId);
});
socket.on('new-message', (message: Message) => {
setMessages(prev => [...prev, message]);
});
socket.on('user-typing', ({ userName }: { userName: string }) => {
setTypingUsers(prev => [...new Set([...prev, userName])]);
setTimeout(() => {
setTypingUsers(prev => prev.filter(u => u !== userName));
}, 2000);
});
socketRef.current = socket;
return () => {
socket.emit('leave-channel', channelId);
socket.disconnect();
};
}, [channelId, token]);
const sendMessage = (content: string) => {
socketRef.current?.emit('send-message', { channelId, content });
};
const sendTyping = () => {
socketRef.current?.emit('typing', channelId);
};
return { messages, sendMessage, sendTyping, typingUsers };
}
Socket.io's binary support is worth noting for applications that transmit images, audio, or file data over WebSockets. You can emit Buffer objects directly, and Socket.io handles the binary framing. This avoids base64 encoding overhead that would otherwise double the size of binary payloads.
Multi-server scaling is Socket.io's main operational consideration. A single Node.js process has a connection limit, and sticky sessions are required when you run multiple instances behind a load balancer. The Redis adapter handles this:
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));
With the Redis adapter, emit events from any server instance and they fan out to all connected clients regardless of which server they are connected to.
PartyKit — Edge-Native WebSockets
Hosted PartyKit stopped accepting deploys on October 16, 2026. The managed service closed on October 23, 2026, and the PartyKit CLI stopped deploying to customer Cloudflare accounts that day. Workers already deployed to your own Cloudflare account can keep running. Deploy new rooms with PartyServer and Wrangler.
If your chat is moving from a hosted project, start from any room data you exported before shutdown. For a Worker that already lives in your account, follow the PartyKit migration guide before changing its bindings or storage. The example below creates a new Worker with SQLite-backed Durable Objects.
npm install partyserver partysocket
npm install -D wrangler
This room stores recent chat messages in Durable Object storage and sends the saved history to a new connection. In PartyServer, onMessage receives the sender first and this.ctx.storage replaces this.room.storage.
// src/server.ts
import { Server, routePartykitRequest, type Connection } from 'partyserver';
type Env = { Main: DurableObjectNamespace<ChatRoom> };
type ChatMessage = { content: string; timestamp: string };
export class ChatRoom extends Server<Env> {
async onConnect(connection: Connection) {
const messages = (await this.ctx.storage.get<ChatMessage[]>('messages')) ?? [];
connection.send(JSON.stringify({ type: 'history', messages }));
}
async onMessage(_sender: Connection, content: string | ArrayBuffer) {
if (typeof content !== 'string' || !content.trim()) return;
const message = { content, timestamp: new Date().toISOString() };
const messages = (await this.ctx.storage.get<ChatMessage[]>('messages')) ?? [];
await this.ctx.storage.put('messages', [...messages.slice(-99), message]);
this.broadcast(JSON.stringify({ type: 'message', message }));
}
}
export default {
async fetch(request: Request, env: Env) {
return (await routePartykitRequest(request, env))
?? new Response('Not found', { status: 404 });
},
} satisfies ExportedHandler<Env>;
Save this as wrangler.jsonc. The Main binding maps to /parties/main/<room>, the default route used by PartySocket.
{
"name": "realtime-chat",
"main": "src/server.ts",
"compatibility_date": "2025-06-01",
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [{ "name": "Main", "class_name": "ChatRoom" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["ChatRoom"] }]
}
Run npx wrangler dev. Add this client to an app whose dev server resolves npm imports, then open the app in two tabs with access to the local Worker.
import PartySocket from 'partysocket';
const socket = new PartySocket({ host: 'localhost:8787', room: 'lobby' });
socket.addEventListener('open', () => console.log('Connected to lobby'));
socket.addEventListener('message', ({ data }) => console.log(JSON.parse(data)));
window.chat = socket;
Once both tabs connect, call chat.send('room check') in one tab. Both should log the message. Reload the other tab and check that the history event includes the message. Open a fresh room by changing room in that tab and confirm its history is empty. The example keeps up to 100 messages per room. Before exposing it publicly, authenticate connections and enforce room access and message limits in the Worker.
When the room checks pass, use npx wrangler deploy to deploy to your Cloudflare account. Set the PartySocket host to your Worker hostname and keep the configured room name.
Yjs for Collaborative Editing with CRDTs
Yjs is not a WebSocket library — it is a conflict-free replicated data type (CRDT) library. A CRDT is a data structure designed so that multiple users can make changes simultaneously, and those changes can always be merged without conflicts, regardless of the order they are received.
This is the technology behind Google Docs, Notion, and Figma's collaborative editing. When two users edit the same document simultaneously, the CRDT ensures their changes merge correctly rather than one overwriting the other. There are no "merge conflicts" in the code editor sense — the algorithm is mathematically guaranteed to converge to the same state on all clients.
Yjs provides shared data types: Y.Text for text documents, Y.Map for key-value structures, Y.Array for ordered lists, and Y.XmlFragment for structured document trees. You connect these to your editor or data model, and Yjs handles the synchronization.
npm install yjs y-websocket
// Collaborative text editor with Yjs + y-websocket
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Collaboration from '@tiptap/extension-collaboration';
import CollaborationCursor from '@tiptap/extension-collaboration-cursor';
import { useMemo, useEffect } from 'react';
interface CollaborativeEditorProps {
documentId: string;
userId: string;
userName: string;
userColor: string;
}
export function CollaborativeEditor({
documentId,
userId,
userName,
userColor,
}: CollaborativeEditorProps) {
const ydoc = useMemo(() => new Y.Doc(), [documentId]);
const provider = useMemo(
() =>
new WebsocketProvider(
process.env.NEXT_PUBLIC_YJS_SERVER_URL!,
`document-${documentId}`,
ydoc
),
[documentId, ydoc]
);
const editor = useEditor({
extensions: [
StarterKit.configure({ history: false }), // Yjs handles history
Collaboration.configure({ document: ydoc }),
CollaborationCursor.configure({
provider,
user: { name: userName, color: userColor },
}),
],
});
useEffect(() => {
return () => {
provider.disconnect();
ydoc.destroy();
};
}, [provider, ydoc]);
return <EditorContent editor={editor} />;
}
// Y.Map for collaborative presence / shared state
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
const ydoc = new Y.Doc();
const provider = new WebsocketProvider(WS_URL, 'room-' + roomId, ydoc);
// Shared cursor positions map
const awareness = provider.awareness;
// Set own cursor position
awareness.setLocalStateField('cursor', {
user: { name: userName, color: '#2563eb' },
position: { x: 100, y: 200 },
});
// React to other users' state
awareness.on('change', () => {
const states = Array.from(awareness.getStates().entries());
const cursors = states
.filter(([clientId]) => clientId !== ydoc.clientID)
.map(([, state]) => state.cursor)
.filter(Boolean);
renderCursors(cursors);
});
Keep your Y.Doc and select a provider for its transport. Use y-websocket with a compatible self-hosted WebSocket server, y-partyserver on Cloudflare, or y-webrtc for peer-to-peer data exchange.
On Cloudflare, export a YServer from y-partyserver and bind it in Wrangler as a Durable Object. Point the browser's y-partyserver/provider at that binding and use the document ID as its room name. Decide how to persist document state with onLoad and onSave before testing a reload with every editor disconnected.
The y-webrtc provider is worth knowing about for specific use cases: it connects clients directly peer-to-peer using WebRTC data channels, with a lightweight signaling server to establish the initial connection. Once connected, no server is involved in data exchange. This makes it free to operate at any scale, with the trade-off that WebRTC connectivity is less reliable than server-based WebSockets in restricted network environments (corporate firewalls, strict NAT configurations).
Yjs's offline support is another capability that sets it apart from event-based real-time systems. A Y.Doc accumulates changes locally when offline. When the network reconnects, it syncs all accumulated changes with remote peers, and the CRDT algorithm guarantees correct merging even when those offline changes interleave with changes made by other users during the disconnection. This is the same model that powers Figma's offline editing — you can close your laptop, make changes on the train, and open it back up to see your changes merge seamlessly with your team's work.
Follow the Yjs provider documentation for the Cloudflare client and server setup.
Ably for Managed Pub/Sub
Ably is a managed real-time messaging platform. Instead of running WebSocket servers, you publish messages to Ably's global network and subscribe to channels. Ably handles delivery guarantees, message ordering, connection management, and geographic distribution.
The npm package integrates with Ably's hosted infrastructure:
npm install ably
// Ably — publish/subscribe
import Ably from 'ably';
// Initialize with API key (server-side) or JWT (client-side for security)
const client = new Ably.Realtime({
key: process.env.ABLY_API_KEY,
// For production: use token auth
authUrl: '/api/ably-token',
});
// Subscribe to a channel
const channel = client.channels.get('notifications:user-123');
channel.subscribe('order-update', (message) => {
console.log('Order update:', message.data);
updateOrderStatus(message.data);
});
// Publish a message (server-side)
await channel.publish('order-update', {
orderId: 'ord_123',
status: 'shipped',
trackingNumber: '1Z999AA10123456784',
});
// Ably — presence (who is online)
const channel = client.channels.get('workspace:abc');
// Enter presence
await channel.presence.enter({ userId: currentUser.id, name: currentUser.name });
// Get current members
const members = await channel.presence.get();
console.log('Online:', members.map(m => m.data.name));
// Subscribe to presence changes
channel.presence.subscribe('enter', (member) => {
console.log(`${member.data.name} came online`);
});
channel.presence.subscribe('leave', (member) => {
console.log(`${member.data.name} went offline`);
});
Ably's free tier covers 6 million messages per month, which is enough for small applications and development. Pricing scales with message volume beyond that. The value proposition is zero WebSocket infrastructure: no servers, no Redis, no ops.
The limitation is the dependency on Ably's infrastructure. If Ably has an outage, your real-time features go down. For most applications this is acceptable (uptime SLAs are strong), but for applications where real-time is the core product, some teams prefer the control of self-hosted Socket.io.
Package Health
| Package | Runs where | What your app manages |
|---|---|---|
socket.io | Node.js server | WebSocket host, room events, and multi-server adapters |
partyserver | Worker and Durable Objects in your Cloudflare account | Worker deploy, room routing, and any stored history |
yjs | Editor clients and the provider you choose | Document sync, presence, and persistence through the provider |
ably | Ably's managed service | Channel names, permissions, and application events |
Comparison Table
| Socket.io | PartyServer | Yjs | Ably | |
|---|---|---|---|---|
| Infrastructure | Your Node.js server | Your Cloudflare Worker | Depends on provider | Managed service |
| Collaborative document merging | Add a CRDT | Add Yjs with y-partyserver | Core feature | Add a CRDT |
| Rooms / channels | Socket.io rooms | Named Durable Objects | Document rooms in the provider | Ably channels |
| Presence | Track connected clients | Track room connections | Awareness protocol | Built in |
| Persistence | Write history to your database | Store history in the Durable Object | Persist CRDT state through the provider | Configure channel history |
| Multi-server fan-out | Redis adapter | Route clients to the same named room | Depends on provider | Managed |
When to Choose
Socket.io is the right choice when you are already running a Node.js server (Express, Fastify, Hono) and want to add WebSocket functionality without introducing external managed services. The rooms and namespaces model handles chat, notifications, live dashboards, and multiplayer features cleanly. Add the Redis adapter when you need to run more than one server instance.
PartyServer fits when you want custom room logic and can deploy a Worker to your Cloudflare account. Check that reconnecting clients get stored state and that a second room gets its own state.
Yjs fits when clients can edit the same document at once. Use y-websocket with a self-hosted backend or y-partyserver with PartyServer. Test that two editors converge after one reconnects with offline changes.
Ably is the right choice when you want zero WebSocket infrastructure and are comfortable with a managed service dependency. The 6M free message tier is generous enough for development and small applications. Ably's pub/sub model, presence, and guaranteed delivery make it practical for fan-out use cases (notify thousands of clients) where self-hosted Socket.io would require careful capacity planning.
| Scenario | Tool |
|---|---|
| Chat app on Node.js server | Socket.io |
| Live notifications, self-hosted | Socket.io |
| Cloudflare rooms with custom logic | PartyServer |
| Collaborative text editor | Yjs with y-websocket or y-partyserver |
| Collaborative whiteboard/drawing | Yjs |
| Managed pub/sub, no infrastructure | Ably |
| Fan-out to thousands of clients | Ably |
| Multi-server Node.js app | Socket.io + Redis adapter |
Before choosing, test the failure that matters to your feature. Reconnect a chat client after it misses an event, or reconnect an editor after both clients change the document offline. The result tells you whether you need message history, document merge logic, or both.