alejotoro-o

payload real time

by alejotoro-o
Other
v3
^3.37.0
MIT

Overview

Summary generated from the README

Adds a websocket server to Payload that emits events when documents in chosen collections are created or updated. Events can be scoped to rooms such as per user or per chat, and JWT authentication for socket connections is optional. A React hook and a client class let frontends subscribe to collection events or custom events. Requires Payload 3.37 or later.

Features

  • Emits create and update events per configured collection
  • Room function scopes events to a user, chat or other group
  • Optional JWT authentication for socket connections
  • useRealtime React hook and PayloadRealtimeClient for subscribing
  • Custom events through client emit and on methods
  • Configurable server port and CORS, with instance exposed on

Use cases

  • Show new notifications to a user instantly without polling
  • Build chat features with room-scoped messages and presence
  • Push live collection updates to dashboards or other open clients

From the author

This plugin provides an implementation of websockets to enable real-time events in Payload CMS collections.

Installation

npm i @alejotoro-o/payload-real-time

30

Stars

0

Forks

1

Open Issues

11 months ago

Last Updated

64

Weekly Downloads

v1.2.0

npm Version

46.8 KB

Unpacked Size

3

Dependencies

GitHub stars

30+2 since Sep 7

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 202630
Dec 5, 202630
Dec 4, 202630
Dec 3, 202630
Dec 2, 202630
Dec 1, 202630
Nov 30, 202630
Nov 29, 202630
Nov 28, 202630
Nov 27, 202630
Nov 26, 202630
Nov 25, 202630
Nov 24, 202630
Nov 23, 202630
Nov 22, 202630
Nov 21, 202630
Nov 20, 202630
Nov 19, 202630
Nov 18, 202630
Nov 17, 202630
Nov 16, 202630
Nov 15, 202630
Nov 14, 202630
Nov 13, 202630
Nov 12, 202630
Nov 11, 202630
Nov 10, 202630
Nov 9, 202630
Nov 8, 202630
Nov 7, 202630
Nov 6, 202630
Nov 5, 202630
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202630
Oct 23, 202630
Oct 22, 202630
Oct 21, 202630
Oct 20, 202630
Oct 19, 202630
Oct 18, 202630
Oct 17, 202630
Oct 16, 202630
Oct 15, 202630
Oct 14, 202630
Oct 13, 202630
Oct 12, 202630
Oct 11, 202630
Oct 10, 202630
Oct 9, 202630
Oct 8, 202630
Oct 7, 202630
Oct 6, 202630
Oct 5, 202630
Oct 4, 202630
Oct 3, 202630
Oct 2, 202630
Oct 1, 202630
Sep 30, 202630
Sep 29, 202630
Sep 28, 202630
Sep 27, 202630
Sep 26, 202630
Sep 25, 202630
Sep 24, 202630
Sep 23, 202630
Sep 22, 202630
Sep 21, 202630
Sep 20, 202630
Sep 19, 202630
Sep 18, 202630
Sep 17, 202630
Sep 16, 202630
Sep 15, 202630
Sep 14, 202630
Sep 13, 202630
Sep 12, 202630
Sep 11, 202630
Sep 10, 202630
Sep 9, 202629
Sep 8, 202628
Sep 7, 202628
npm weekly downloads

69−8 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 202669
Dec 5, 202671
Dec 4, 202689
Dec 3, 2026112
Dec 2, 2026138
Dec 1, 2026163
Nov 30, 2026174
Nov 29, 2026162
Nov 28, 2026153
Nov 27, 2026132
Nov 26, 2026116
Nov 25, 2026101
Nov 24, 202667
Nov 23, 202652
Nov 22, 202662
Nov 21, 202663
Nov 20, 202688
Nov 19, 202685
Nov 18, 2026103
Nov 17, 2026100
Nov 16, 202695
Nov 15, 202679
Nov 14, 202681
Nov 13, 202667
Nov 12, 202683
Nov 11, 202691
Nov 10, 2026106
Nov 9, 2026112
Nov 8, 2026125
Nov 7, 2026151
Nov 6, 2026151
Nov 5, 2026147
Nov 4, 2026119
Nov 3, 2026118
Nov 2, 2026118
Nov 1, 2026119
Oct 31, 202691
Oct 30, 202683
Oct 29, 202662
Oct 28, 202653
Oct 27, 202642
Oct 26, 202643
Oct 25, 202631
Oct 24, 202624
Oct 23, 202615
Oct 22, 202637
Oct 21, 202654
Oct 20, 202651
Oct 19, 202646
Oct 18, 202647
Oct 17, 202663
Oct 16, 202667
Oct 15, 202651
Oct 14, 202643
Oct 13, 202644
Oct 12, 202649
Oct 11, 202650
Oct 10, 202646
Oct 9, 202654
Oct 8, 202662
Oct 7, 202654
Oct 6, 202656
Oct 5, 202650
Oct 4, 202655
Oct 3, 202645
Oct 2, 202644
Oct 1, 202653
Sep 30, 202666
Sep 29, 2026104
Sep 28, 2026106
Sep 27, 202698
Sep 26, 2026144
Sep 25, 2026133
Sep 24, 2026114
Sep 23, 2026104
Sep 22, 202663
Sep 21, 202669
Sep 20, 202670
Sep 19, 202632
Sep 18, 202650
Sep 17, 202657
Sep 16, 202654
Sep 15, 202653
Sep 14, 202645
Sep 13, 202650
Sep 12, 202645
Sep 11, 202649
Sep 10, 202647
Sep 9, 202660
Sep 8, 202672
Sep 7, 202677

Each point is npm's rolling 7-day download count.

Health Score

55/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1088989388-root.svg)](https://payloaddirectory.dev/plugins/1088989388-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1088989388-root"><img src="https://payloaddirectory.dev/badge/1088989388-root.svg" alt="Payload Directory"></a>
Updated Dec 31, 2025Created Nov 3, 2025Published Dec 31, 2025

README

Payload Real-time Plugin

This plugin provides an implementation of websockets to enable real-time events in Payload CMS collections.

Installation

Install the package running:

npm install @alejotoro-o/payload-real-time

NOTE: On some implementation you can get the error [TypeError: bufferUtil.unmask is not a function], in that case you need to install the bufferutil package with npm install bufferutil.

What This Plugin Does

  • Emits real-time events when documents are created or updated.
  • Scopes events to custom rooms (e.g. per user, per chat).
  • Provides a React hook (useRealtime) for subscribing to events.
  • Includes a flexible client for custom event handling.

How to use the plugin

First configure the plugin in payload.config.ts. The plugin accepts a configuration object with the following shape:

export type PayloadRealTimeConfig = {
    collections?: { [K in CollectionSlug]?: {
        room: (
            doc: Extract<DefinedCollections[number], { slug: K }>['fields'],
            operation?: 'create' | 'update',
            previousDoc?: Extract<DefinedCollections[number], { slug: K }>['fields'],
        ) => string | undefined,
        events?: Array<'create' | 'update'>
    } }
    serverOptions?: {
        port?: number,
        cors?: {
            origin: string | string[],
            methods?: string | string[],
        }
    }
    requireAuth?: boolean,
    disabled?: boolean,
}
  • collections: Define which collections should emit real-time events. For each collection, you can specify:

    • events: Limit which operations trigger events. Use 'create', 'update', or both. If omitted, all operations will emit.
    • room: A function that receives the resulting document, the operation being performed in the collection and the previous document; the function returns a room string. This scopes the event to a specific room (e.g. user:{userId}).
  • serverOptions: Customize the WebSocket server:

    • port: Port to run the server on (default is 3001)
    • cors: CORS configuration (e.g. { origin: '*' })
  • requireAuth: Set to true to enable JWT authentication for socket connections. Default is false.

  • disabled: Set to true to disable the plugin entirely.

Here is an example configuring the plugin to emit events when documents are created or updated in the notifications collection.

import payloadRealTime from '@alejotoro-o/payload-real-time'

export const config = buildConfig({
    // ... Payload config options
    plugins: [
        payloadRealTime({
            collections: {
                notifications: {
                    room: (doc: Notification) => {
                        const user = doc.user
                        const userId = typeof user === 'number' ? user : user?.id
                        return userId ? `user:${userId}` : undefined
                    },
                    events: ['create', 'update'],
                },
            },
            requireAuth: true
        }),
    ],
})

Use the useRealtime hook to subscribe to events in your frontend:

'use client'

import { User } from "payload-types.js"
import { useEffect, useState } from "react"
import { useRealtime } from "../../../src/client/useRealtime.js"

export default function Page() {

    const [user, setUser] = useState<User>()
    const [token, setToken] = useState()
    const realtime = useRealtime(user?.id.toString() ?? '', token ?? '')
    const [message, setMessage] = useState()

    useEffect(() => {
        const getUser = async () => {
            const response = await fetch('http://localhost:3000/api/users/me')
            if (response.ok) {
                const user = await response.json()
                setUser(user.user)
                setToken(user.token)
            } else {
                console.log('Error')
            }
        }
        getUser()
    }, [])

    // Websockets
    useEffect(() => {
        if (!user || !realtime) return
        realtime.join(`user:${user.id}`)
        realtime.onCollection('notifications', (data) => {
            console.log(data.data)
            setMessage(data.data.message)
        })
    }, [user, realtime])

    return (
        <div>
            <div>
                {user?.email}
            </div>
            <div>
                {message}
            </div>
        </div>
    )
}

API Overview

useRealtime(userId: string, token?: string): PayloadRealtimeClient

A React hook that initializes a real-time client, identifies the user for presence tracking, and returns a PayloadRealtimeClient instance.

Use this in components to manage socket lifecycle automatically:

const realtime = useRealtime(user.id, user.token)

PayloadRealtimeClient

You can also instantiate the client manually:

import { PayloadRealtimeClient } from '@alejotoro-o/payload-real-time'

const client = new PayloadRealtimeClient({ url, token })
Constructor Options
type RealtimeClientOptions = {
    url?: string        // WebSocket server URL (default: http://localhost:3001)
    token?: string      // Optional JWT for authentication
}

Client Methods

MethodDescription
identify(userId: string)Identifies the user and registers them for presence tracking. Should be called once after connecting.
join(roomId: string)Joins a specific room (e.g. user:123, chat:abc). Enables receiving events scoped to that room.
leave(roomId: string)Leaves a previously joined room. Useful for cleaning up listeners when navigating away.
onCollection(slug: string, callback: (data) => void)Subscribes to real-time events for a specific collection. Events are emitted as realtime:{slug}.
on(event: string, callback: (data) => void)Subscribes to any custom event. Useful for chat messages, typing indicators, etc.
emit(event: string, data: any)Emits a custom event to the server. The payload should include a roomId if it's meant to be scoped.
disconnect()Gracefully disconnects the socket. Useful on logout or component unmount.

Example: Custom Event

client.emit('chat-message', {
    roomId: 'chat:abc123',
    content: 'Hello world!',
})
client.on('chat-message', (data) => {
    console.log('New message:', data.content)
})

Server-side Usage

The plugin attaches the Socket.IO server instance to payload.io, allowing you to emit events from any hook or endpoint:

const io = (payload as any).io

io.to(`user:${userId}`).emit('custom-event', { message: 'Hello!' })

Similar plugins