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

payload-websocket

v1.0.0

Published

WebSocket manager for Payload CMS with authentication, rooms, and real-time broadcasting

Readme

payload-websocket

WebSocket manager for Payload CMS with authentication, rooms, and real-time broadcasting - Socket.io style API.

✨ Features

  • 🔐 Mandatory Authentication with Payload CMS
  • 🏠 Rooms (Socket.io style)
  • 📡 Broadcasting to users, rooms, or all clients
  • 🔌 Multiple connections per user
  • 📘 Full TypeScript support
  • 🎯 Easy integration with Payload hooks
  • Zero dependencies (uses peer dependencies)

📦 Installation

npm install payload-websocket
# or
pnpm add payload-websocket
# or
yarn add payload-websocket

Peer Dependencies

Make sure you have these installed:

npm install next next-ws payload ws
npm install -D @types/ws

Configure next.config.mjs

import { withPayload } from '@payloadcms/next/withPayload'
import nextWebSocket from 'next-ws/server'

/** @type {import('next').NextConfig} */
const nextConfig = {
  // ... your config
}

// Apply next-ws FIRST, then Payload
export default nextWebSocket(withPayload(nextConfig))

🚀 Quick Start

1. Create WebSocket Route

Create src/app/api/ws/route.ts:

import { createWebSocketRoute } from 'payload-websocket'
import configPromise from '@payload-config'

const { GET, UPGRADE } = createWebSocketRoute({
  payloadConfig: configPromise,
})

export { GET, UPGRADE }

That's it! You now have a fully functional WebSocket server with authentication.


🔐 Authentication

All WebSocket connections require authentication. Three methods supported:

1. Cookie (Automatic in Admin Panel)

const ws = new WebSocket('ws://localhost:3000/api/ws')
// Uses payload-token cookie automatically

2. Query Parameter

const ws = new WebSocket(`ws://localhost:3000/api/ws?token=${token}`)

3. Authorization Header

const ws = new WebSocket('ws://localhost:3000/api/ws', {
  headers: {
    Authorization: `Bearer ${token}`
  }
})

📨 Client Messages

Join a Room

ws.send(JSON.stringify({
  type: 'join',
  room: 'room-name'
}))

Leave a Room

ws.send(JSON.stringify({
  type: 'leave',
  room: 'room-name'
}))

Send Message to Room

ws.send(JSON.stringify({
  type: 'message',
  room: 'room-name',
  event: 'my-event',
  data: { message: 'Hello!' }
}))

Broadcast to All

ws.send(JSON.stringify({
  type: 'broadcast',
  event: 'announcement',
  data: { text: 'Important update!' }
}))

Get Connection Stats

ws.send(JSON.stringify({ type: 'stats' }))

🎯 Server-side Broadcasting

In Payload Hooks

import { broadcastToRoom, broadcastToUser } from 'payload-websocket'

export const Tasks: CollectionConfig = {
  slug: 'tasks',
  fields: [
    { name: 'title', type: 'text' },
    { name: 'completed', type: 'checkbox' },
  ],
  hooks: {
    afterChange: [
      async ({ doc, operation }) => {
        // Broadcast to all users in the 'tasks' room
        broadcastToRoom('tasks', 'task:changed', {
          id: doc.id,
          title: doc.title,
          completed: doc.completed,
          operation, // 'create' or 'update'
        })

        return doc
      },
    ],
  },
}

Available Broadcasting Functions

import {
  broadcastToUser,      // Send to specific user (all their connections)
  broadcastToRoom,      // Send to all in a room
  broadcastToAllUsers,  // Send to everyone
  emitToSocket,         // Send to specific socket
} from 'payload-websocket'

// Examples:
broadcastToUser('user-id', 'notification', { message: 'Hello!' })
broadcastToRoom('chat-room', 'new-message', { text: 'Hi there!' })
broadcastToAllUsers('announcement', { text: 'Server maintenance soon' })

⚙️ Advanced Configuration

Custom Message Handler

import { createWebSocketRoute } from 'payload-websocket'
import configPromise from '@payload-config'

const { GET, UPGRADE } = createWebSocketRoute({
  payloadConfig: configPromise,
  
  // Custom message handler
  onMessage: async (client, message, userId) => {
    console.log(`User ${userId} sent:`, message)
    
    if (message.type === 'custom-action') {
      // Your custom logic
      client.send(JSON.stringify({
        event: 'custom-response',
        data: { success: true }
      }))
    }
  },
  
  // Custom connection handler
  onConnect: async (client, userId) => {
    console.log(`User ${userId} connected`)
    // Auto-join user to their personal room
    joinRoom(client, `user:${userId}`)
  },
  
  // Custom disconnect handler
  onDisconnect: async (userId, code, reason) => {
    console.log(`User ${userId} disconnected: ${reason}`)
  },
  
  // Custom cookie name
  cookieName: 'my-custom-token',
})

export { GET, UPGRADE }

🎨 Frontend Example (React)

'use client'

import { useEffect, useState, useRef } from 'react'

export default function RealtimeTasks() {
  const [tasks, setTasks] = useState([])
  const ws = useRef<WebSocket | null>(null)

  useEffect(() => {
    // Load initial data
    fetch('/api/tasks')
      .then(res => res.json())
      .then(data => setTasks(data.docs))

    // Connect WebSocket
    ws.current = new WebSocket('ws://localhost:3000/api/ws')

    ws.current.onmessage = (event) => {
      const msg = JSON.parse(event.data)

      if (msg.event === 'ws:ready') {
        // Join tasks room
        ws.current?.send(JSON.stringify({
          type: 'join',
          room: 'tasks'
        }))
      }

      if (msg.event === 'task:changed') {
        // Update task in real-time
        setTasks(prev => {
          const exists = prev.find(t => t.id === msg.data.id)
          if (exists) {
            return prev.map(t => t.id === msg.data.id ? msg.data : t)
          } else {
            return [...prev, msg.data]
          }
        })
      }
    }

    return () => ws.current?.close()
  }, [])

  return (
    <div>
      <h1>Real-time Tasks</h1>
      {tasks.map(task => (
        <div key={task.id}>
          {task.title} - {task.completed ? '✅' : '⏳'}
        </div>
      ))}
    </div>
  )
}

📚 API Reference

Broadcasting Functions

broadcastToUser(userId, event, data)

Send to all connections of a specific user.

broadcastToRoom(roomName, event, data, except?)

Send to all sockets in a room, optionally excluding one.

broadcastToAllUsers(event, data)

Send to all connected clients.

emitToSocket(socket, event, data)

Send to a specific socket.

Room Functions

joinRoom(socket, roomName)

Add socket to a room.

leaveRoom(socket, roomName)

Remove socket from a room.

leaveAllRooms(socket)

Remove socket from all rooms.

getRoomSockets(roomName)

Get all sockets in a room.

getSocketRooms(socket)

Get all rooms a socket is in.

Utility Functions

getConnectionStats()

Get connection statistics.

debugConnections()

Log all connections for debugging.


� Support & Donations

This project is free and open source for non-commercial use. If you find it useful, please consider supporting its development:

💰 Donate

🤝 Other Ways to Support

  • ⭐ Star this repository
  • 🐛 Report bugs and issues
  • 📝 Contribute to documentation
  • 💡 Share feature ideas
  • 🔀 Submit pull requests

📄 License

Non-Commercial License - Free for non-commercial use only.

This software may NOT be used for commercial purposes without explicit permission.

  • ✅ Free for personal projects
  • ✅ Free for educational use
  • ✅ Free for open-source projects
  • ❌ Cannot be sold or commercialized
  • ❌ Cannot be used in paid products/services

For commercial licensing, please contact: [email protected]

See LICENSE for full details.


👤 Author

Erick Pajares
Digital Andes Perú


🤝 Contributing

Issues and PRs welcome!


Made with ❤️ by Erick Pajares - Digital Andes Perú