New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

playsocketjs

Package Overview
Dependencies
Maintainers
1
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

playsocketjs

WebSocket wrapper for creating simple multiplayer systems with ease.

latest
Source
npmnpm
Version
3.1.2
Version published
Maintainers
1
Created
Source

PlaySocket Client

A reactive, optimistic WebSocket library that simplifies game & app development by abstracting away complex sync logic.

Why use PlaySocket?

PlaySocket eliminates the traditional complexity of collaborative experiences:

  • Streamlined architecture: No additional backend code is required, but server-authoritative behavior supported
  • State synchronization: Built-in storage system keeps the full state synchronized across all clients, always conflict-free and in order
  • Resilient & secure connections: Automatic reconnection handling & strict rate-limiting
  • Lightweight: Uses WebSockets for efficient, predictable, reliable communication and has little dependencies

Installation

npm install playsocketjs

Usage examples

Note that in production, you should always try...catch promises, such as socket.init() – they can reject!

Initializing the client:

import PlaySocket from 'playsocketjs';

// Create a new instance
const socket = new PlaySocket('unique-client-id', { // You can pass no ID to let the server pick one
    endpoint: 'wss://example.com/socket'
});

// Set up event handlers (optional)
socket.onEvent('status', status => console.log('Status:', status));
socket.onEvent('error', status => console.log('Error:', status));

const clientId = await socket.init(); // Initialize the socket

Creating a room:

// Create a new room
const roomId = await socket.createRoom();

// Optionally, with initial storage
const roomId = await socket.createRoom({
  players: ["this-player"],
  latestPlayer: null,
});

Joining a room:

await socket.joinRoom('room-id'); // Join an existing room

Leaving a room:

socket.destroy(); // To leave the room, destroy the instance

Using the storage update event for reactivity:

const reactiveVariable = useState(); // Or $state(), reactive(), depending on your framework
socket.onEvent('storageUpdated', storage => (reactiveVariable = storage)); // Assign on update

Interfacing with the synchronized storage (examples):

const currentState = socket.storage; // Synchronous, local access
socket.updateStorage('players', 'array-add-unique', { username: 'Player4', level: 2 }); // Special method to enable conflict-free additions for arrays
socket.updateStorage('latestPlayer', 'set', 'Player4'); // Regular synced storage update

Sending traditional requests to the server:

socket.sendRequest('chosen-request-name', { fact: "You can build server-authoritative logic using this!" })

API reference

Constructor

Creates a new PlaySocket instance with a specified ID and configuration options. The ID can be set to null to let the server pick a unique one.

new PlaySocket(id?: string, options: PlaySocketOptions)

Configuration options

OptionTypeDefaultDescription
endpointstringundefinedWebSocket server endpoint (e.g., 'wss://example.com/socket') (required)
customDataobject{}Arbitrary data to pass to the "clientRegistered" server event
debugbooleanfalseSet to true to enable extra logging

Methods

MethodParametersReturn typeDescription
init()-Promise<string>Initialize the WebSocket connection – Returns a promise which resolves with the client's ID
createRoom()initialStorage?: object, size?: numberPromise<string>Create a new room and become host – Returns a promise which resolves with the room ID. The room participant maximum is 100
joinRoom()roomId: stringPromise<void>Join an existing room
destroy()-voidUse this to leave a room and close the connection
updateStorage()key: string, type: 'set' | 'array-add' | 'array-add-unique' | 'array-remove-matching' | 'array-update-matching', value: any, updateValue?: anyvoidUpdate a key in the shared storage (max. 100 keys). Array operation types allow for conflict-free simultaneous array updates. For '-matching' operations, value becomes the value to match, and updateValue the replacement
sendRequest()name: string, data?: anyvoidSend requests to the server with optional custom data (handle them in the requestReceived server event)
onEvent()event: string, callback: FunctionvoidRegister an event callback

Event types

EventCallback parameterDescription
statusstatus: stringConnection status updates
errorerror: stringError events
movedroomId: stringMoved to different room
instanceDestroyed-Destruction event - triggered by manual .destroy() method invocation or by fatal errors and disconnects
storageUpdatedstorage: objectStorage state changes
hostMigratedroomId: stringHost changes
clientJoinedclientId: stringNew client joined the room
clientLeftclientId: string, roomId?: stringClient left the room

Properties (Read-only)

PropertyTypeDescription
idstringClient's unique identifier on the WebSocket server
isHostbooleanIf this user is currently assigned the host role
participantCountnumberNumber of active client connections in room (with yourself)
storageobjectRetrieve storage object

 

PlaySocket Server

PlaySocket includes a server implementation that can be set up in seconds.

Installation

To use the server component, you'll need to install playsocketjs and the ws package:

npm install playsocketjs ws

Usage examples

Here are usage examples for a standalone server and an Express.js application.

Standalone server

import PlaySocketServer from 'playsocketjs/server'; // Both ES Module & CommonJS Module syntax is supported

const server = new PlaySocketServer(); // Create and start the server (default path is /)

// Gracefully disconnect all clients and close the server (optional)
function shutdown() {
    server.stop();
    process.exit(0);
}

// Handle both SIGINT and SIGTERM
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

Together with Express.js (or other Backend frameworks)

const express = require('express');
const http = require('http');
const PlaySocketServer = require('playsocketjs/server');

const app = express();
const httpServer = http.createServer(app);

// Create PlaySocket server with your HTTP server
const playSocketServer = new PlaySocketServer({
  server: httpServer,
  path: '/socket'
});

// Start the server
httpServer.listen(3000, () => {
  console.log('Server running on port 3000');
});

// Gracefully disconnect all clients and close the server (recommended)
function shutdown() {
    server.stop();
    process.exit(0);
}

// Handle both SIGINT and SIGTERM
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

API reference

Constructor

Creates a new PlaySocket Server instance with configuration options.

new PlaySocket(options: PlaySocketServerOptions)

Configuration options

OptionTypeDefaultDescription
portnumber3000Port to listen on (used only if no server provided)
pathstring'/'WebSocket endpoint path
serverhttp.Server-Existing http server (optional)
rateLimitnumber20Adjust the messages/second rate limit
debugbooleanfalseSet to true to enable extra logging
verifyClientfunction-Optional callback to verify connections before WebSocket upgrade

verifyClient callback

The verifyClient option allows you to implement custom connection verification logic, such as rate limiting, before the WebSocket handshake completes.

const server = new PlaySocketServer({
    server: httpServer,
    path: '/socket',
    verifyClient: (info, callback) => {
        // info.req - the HTTP request object, info.origin - the Origin header value
        const ip = info.req.headers['x-forwarded-for'] || info.req.socket.remoteAddress;
        if (isRateLimited(ip)) return callback(false, 429, 'Too Many Requests');
        callback(true);
    }
});

The callback signature is callback(verified, code?, message?) where code and message are the optional HTTP response status for rejected connections.

Methods

MethodParametersReturn typeDescription
stop()-voidCloses all active client connections, the websocket server and the underlying http server if it's standalone
kick()clientId: string, reason?: stringvoidKick a client by their clientID – this will close their connection and set an error message
move()clientId: string, roomId: stringvoidMove a client, that is already in a room, to a different room
onEvent()event: string, callback: FunctionvoidRegister a server-side event callback
getRoomStorage()roomId: stringobjectGet a snapshot of the current room storage
updateRoomStorage()roomId: string, key: string, type: 'set' | 'array-add' | 'array-add-unique' | 'array-remove-matching' | 'array-update-matching', value: any, updateValue?: anyvoidUpdate a key in the shared room storage from the server
createRoom()initialStorage?: object, size?: number, host?: stringobjectCreate a room (returns object containing room ID and state)
destroyRoom()roomId: stringvoidDestroy a room & kick all participants

Event types

EventCallback parametersDescriptionReturn for action
clientRegisteredclientId: string, customData: objectClient registered with the server-
clientRegistrationRequestedclientId: string, customData: objectClient requests to registerReturn false or rejection reason string to block
clientDisconnectedclientId: stringClient disconnected from the server-
clientJoinedRoomclientId: string, roomId: stringClient joined a room-
clientJoinRequestedclientId: string, roomId: stringClient requests to join a roomReturn false or rejection reason string to block
clientLeftRoomclientId: string, roomId: stringClient left a room-
roomCreatedroomId: stringClient created a room-
roomDestroyedroomId: stringRoom was destroyed (happens when all participants leave, unless room host is "server")-
roomCreationRequested{clientId: string, initialStorage: object}Room creation requested by clientReturn object to override initial storage, false to deny
storageUpdated{clientId: string, roomId: string, update: object, storage: object}Room storage property updated-
storageUpdateRequested{clientId: string, roomId: string, update: object, storage: object}Room storage property update requested by clientReturn false to block the update
requestReceived{clientId: string, roomId?: string, requestName: string, data?: any}Request from client was received by the server-

Properties (Read-only)

PropertyTypeDescription
roomsobjectRetrieve the rooms object

License

MIT

Keywords

WebSocket

FAQs

Package last updated on 08 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts