MCPInstall

websockets

Implement real-time bidirectional communication with Socket.io and ws library for chat, notifications, and live dashboards

Installs
83
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill websockets
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads websockets automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Node.js WebSockets Skill

Master real-time bidirectional communication for building chat apps, live notifications, collaborative tools, and real-time dashboards.

Quick Start

WebSocket server in 3 steps:

  1. Setup Server - Socket.io or ws library
  2. Handle Connections - Manage client lifecycle
  3. Emit Events - Send/receive messages

Core Concepts

Socket.io Server Setup

const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST']
  }
});

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  // Handle events
  socket.on('chat:message', (data) => {
    // Broadcast to all clients
    io.emit('chat:message', {
      ...data,
      timestamp: Date.now()
    });
  });

  // Join rooms
  socket.on('room:join', (roomId) => {
    socket.join(roomId);
    socket.to(roomId).emit('room:user-joined', socket.id);
  });

  // Handle disconnect
  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

httpServer.listen(3000);

Socket.io Client

import { io } from 'socket.io-client';

const socket = io('http://localhost:3000', {
  auth: { token: 'jwt-token-here' }
});

socket.on('connect', () => {
  console.log('Connected:', socket.id);
});

socket.on('chat:message', (message) => {
  console.log('Received:', message);
});

// Send message
socket.emit('chat:message', {
  text: 'Hello!',
  userId: 'user123'
});

Learning Path

Beginner (1-2 weeks)

  • ✅ Socket.io server setup
  • ✅ Basic event emission
  • ✅ Connect/disconnect handling
  • ✅ Simple chat application

Intermediate (3-4 weeks)

  • ✅ Rooms and namespaces
  • ✅ Authentication middleware
  • ✅ Broadcasting patterns
  • ✅ Error handling

Advanced (5-6 weeks)

  • ✅ Horizontal scaling with Redis
  • ✅ Binary data transfer
  • ✅ Reconnection strategies
  • ✅ Performance optimization

Native ws Library

const WebSocket = require('ws');
const { createServer } = require('http');

const server = createServer();
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws, req) => {
  const ip = req.socket.remoteAddress;
  console.log('Client connected from', ip);

  // Handle messages
  ws.on('message', (data) => {
    const message = JSON.parse(data);
    console.log('Received:', message);

    // Echo back
    ws.send(JSON.stringify({
      type: 'echo',
      data: message
    }));
  });

  // Ping/pong heartbeat
  ws.isAlive = true;
  ws.on('pong', () => {
    ws.isAlive = true;
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

// Heartbeat interval
const interval = setInterval(() => {
  wss.clients.forEach((ws) => {
    if (!ws.isAlive) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

wss.on('close', () => clearInterval(interval));

server.listen(3000);

Rooms and Namespaces

// Namespaces for feature separation
const chatNamespace = io.of('/chat');
const notificationsNamespace = io.of('/notifications');

chatNamespace.on('connection', (socket) => {
  // Chat-specific logic
  socket.on('message', (msg) => {
    chatNamespace.emit('message', msg);
  });
});

notificationsNamespace.on('connection', (socket) => {
  // Notification-specific logic
  socket.on('subscribe', (topic) => {
    socket.join(topic);
  });
});

// Rooms within namespace
socket.on('join-channel', (channelId) => {
  socket.join(`channel:${channelId}`);

  // Send only to room
  io.to(`channel:${channelId}`).emit('user-joined', {
    userId: socket.userId,
    channelId
  });
});

// Leave room
socket.on('leave-channel', (channelId) => {
  socket.leave(`channel:${channelId}`);
});

Authentication Middleware

const jwt = require('jsonwebtoken');

// Socket.io middleware
io.use((socket, next) => {
  const token = socket.handshake.auth.token;

  if (!token) {
    return next(new Error('Authentication required'));
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    socket.userId = decoded.id;
    socket.userRole = decoded.role;
    next();
  } catch (err) {
    next(new Error('Invalid token'));
  }
});

// Namespace-level auth
const adminNamespace = io.of('/admin');
adminNamespace.use((socket, next) => {
  if (socket.userRole !== 'admin') {
    return next(new Error('Admin access required'));
  }
  next();
});

Scaling with Redis Adapter

const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');

const pubClient = createClient({ url: 'redis://localhost:6379' });
const subClient = pubClient.duplicate();

Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
  io.adapter(createAdapter(pubClient, subClient));
  console.log('Redis adapter connected');
});

// Now events are broadcast across all server instances
io.emit('notification', { message: 'Hello from any server!' });

Real-Time Patterns

Chat Application

// Server
io.on('connection', (socket) => {
  socket.on('chat:join', ({ room, username }) => {
    socket.join(room);
    socket.to(room).emit('chat:user-joined', { username });
  });

  socket.on('chat:message', ({ room, message }) => {
    io.to(room).emit('chat:message', {
      user: socket.userId,
      message,
      timestamp: Date.now()
    });
  });

  socket.on('chat:typing', ({ room }) => {
    socket.to(room).emit('chat:typing', { user: socket.userId });
  });
});

Live Notifications

// Server
function sendNotification(userId, notification) {
  io.to(`user:${userId}`).emit('notification', notification);
}

// Join user's personal room
socket.on('authenticate', () => {
  socket.join(`user:${socket.userId}`);
});

// From any service
notificationService.on('new', (userId, data) => {
  sendNotification(userId, data);
});

Live Dashboard

// Server: broadcast metrics periodically
setInterval(async () => {
  const metrics = await getSystemMetrics();
  io.emit('metrics:update', metrics);
}, 1000);

// Or on-demand updates
database.onChange((change) => {
  io.to(`dashboard:${change.collection}`).emit('data:update', change);
});

Error Handling

// Client-side reconnection
const socket = io({
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000
});

socket.on('connect_error', (err) => {
  console.log('Connection error:', err.message);
});

socket.on('reconnect', (attemptNumber) => {
  console.log('Reconnected after', attemptNumber, 'attempts');
});

socket.on('reconnect_failed', () => {
  console.log('Failed to reconnect');
  // Fallback to polling or show offline UI
});

// Server-side error handling
socket.on('error', (error) => {
  console.error('Socket error:', error);
});

Unit Test Template

const { createServer } = require('http');
const { Server } = require('socket.io');
const Client = require('socket.io-client');

describe('WebSocket Server', () => {
  let io, serverSocket, clientSocket;

  beforeAll((done) => {
    const httpServer = createServer();
    io = new Server(httpServer);
    httpServer.listen(() => {
      const port = httpServer.address().port;
      clientSocket = Client(`http://localhost:${port}`);
      io.on('connection', (socket) => {
        serverSocket = socket;
      });
      clientSocket.on('connect', done);
    });
  });

  afterAll(() => {
    io.close();
    clientSocket.close();
  });

  it('should receive message from client', (done) => {
    serverSocket.on('hello', (arg) => {
      expect(arg).toBe('world');
      done();
    });
    clientSocket.emit('hello', 'world');
  });

  it('should broadcast to clients', (done) => {
    clientSocket.on('broadcast', (arg) => {
      expect(arg).toBe('everyone');
      done();
    });
    io.emit('broadcast', 'everyone');
  });
});

Troubleshooting

ProblemCauseSolution
Connection dropsNo heartbeatEnable pingInterval/pingTimeout
Messages not receivedWrong roomVerify room membership
Scaling issuesNo RedisAdd Redis adapter
Memory leakListeners not removedClean up on disconnect

When to Use

Use WebSockets when:

  • Real-time bidirectional communication
  • Low-latency updates needed
  • Live notifications/chat
  • Collaborative applications
  • Gaming/trading platforms

Related Skills

  • Express REST API (HTTP fallback)
  • Microservices (distributed events)
  • Redis (pub/sub scaling)

Resources

FAQ

What does the websockets skill do?

Implement real-time bidirectional communication with Socket.io and ws library for chat, notifications, and live dashboards

How do I install websockets?

Run npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill websockets in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/websockets/ (personal) or .claude/skills/websockets/ (project).

Which AI agents can use websockets?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is websockets safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains websockets?

It is published by pluginagentmarketplace in pluginagentmarketplace/custom-plugin-nodejs. It has 83 recorded installs.

More from pluginagentmarketplace/custom-plugin-nodejs

View all →

express-rest-api

pluginagentmarketplace/custom-plugin-nodejs

Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services

Backend & APIs901 installs

mongoose-mongodb

pluginagentmarketplace/custom-plugin-nodejs

Work with MongoDB in Node.js using Mongoose ODM for schema design, CRUD operations, relationships, and advanced queries

Data & Databases694 installs

docker-deployment

pluginagentmarketplace/custom-plugin-nodejs

Containerize and deploy Node.js applications with Docker including multi-stage builds, Docker Compose, and production optimization

DevOps & Cloud523 installs

jwt-authentication

pluginagentmarketplace/custom-plugin-nodejs

Open the skill to read its SKILL.md instructions.

Backend & APIs226 installs

jest-testing

pluginagentmarketplace/custom-plugin-nodejs

Open the skill to read its SKILL.md instructions.

Testing & QA120 installs

async-patterns

pluginagentmarketplace/custom-plugin-nodejs

Master asynchronous programming in Node.js with Promises, async/await, streams, and event-driven patterns for efficient non-blocking operations

Backend & APIs97 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs