A plugin for Strapi CMS that provides the ability for Socket IO integration
The installation requirements are the same as Strapi itself and can be found in the documentation on the Quick Start page in the Prerequisites info card.
- v5.x.x (Current version)
- v4.x.x (Legacy - see older versions)
NOTE: This version (v3.x.x+) is for Strapi v5. For Strapi v4, please use version 2.x.x of this plugin.
npm install strapi-plugin-io
# or
yarn add strapi-plugin-ioConfigure the plugin in your Strapi config file: config/plugins.js (or config/plugins.ts for TypeScript):
module.exports = {
'io': {
enabled: true,
config: {
// Socket IO server options
socket: {
serverOptions: {
cors: {
origin: process.env.CLIENT_URL || 'http://localhost:3000',
methods: ['GET', 'POST']
}
}
},
// Content types to watch for real-time events
contentTypes: [
'api::article.article',
'api::comment.comment',
// or with specific actions:
{
uid: 'api::product.product',
actions: ['create', 'update', 'delete']
}
],
// Custom events
events: [
{
name: 'connection',
handler: ({ strapi, io }, socket) => {
console.log('Socket connected:', socket.id);
}
}
],
// Hooks
hooks: {
init: ({ strapi, $io }) => {
console.log('Socket IO initialized');
}
}
}
}
};The plugin supports two authentication strategies:
- JWT (Users-Permissions): Use JWT tokens from the users-permissions plugin
- API Token: Use Strapi API tokens
import { io } from 'socket.io-client';
// Using JWT (users-permissions)
const socket = io('http://localhost:1337', {
auth: {
strategy: 'jwt',
token: 'your-jwt-token'
}
});
// Using API Token
const socket = io('http://localhost:1337', {
auth: {
strategy: 'api-token',
token: 'your-api-token'
}
});
// Listen for content type events
socket.on('article:create', (data) => {
console.log('New article created:', data);
});
socket.on('article:update', (data) => {
console.log('Article updated:', data);
});
socket.on('article:delete', (data) => {
console.log('Article deleted:', data);
});// Access Socket.IO instance anywhere in your Strapi app
const io = strapi.$io;
// Emit custom events to all clients
strapi.$io.raw({
event: 'notification',
data: { message: 'Hello World!' }
});
// Send private message to specific socket
strapi.$io.sendPrivateMessage(socketId, 'notification', {
type: 'info',
message: 'Payment processed'
});
// Emit to specific namespace
strapi.$io.emitToNamespace('admin', 'dashboard:update', {
stats: { users: 1234, active: 56 }
});
// π NEW: Entity-Specific Subscriptions
// Emit to clients watching a specific entity
strapi.$io.emitToEntity('api::article.article', 123, 'article:viewed', {
views: 1500
});
// Get real-time stats
const monitoringService = strapi.plugin('io').service('monitoring');
const stats = monitoringService.getConnectionStats();
console.log(`Connected: ${stats.connected} clients`);NEW: Subscribe to individual entities for targeted updates!
// Client-side: Subscribe to a specific article
socket.emit('subscribe-entity', {
uid: 'api::article.article',
id: 123
}, (response) => {
if (response.success) {
console.log('Subscribed! Will only receive updates for article 123');
}
});
// Listen for updates (only receives events for article 123)
socket.on('article:update', (data) => {
console.log('Article 123 was updated:', data);
});Benefits:
- π― Only receive updates for entities you're watching
- π Reduced bandwidth and client processing
- β‘ Better performance at scale
- π Built-in permission checks
See USAGE-GUIDE.md for complete examples.
// Join socket to room
strapi.$io.joinRoom(socketId, 'premium-users');
// Get all sockets in room
const sockets = await strapi.$io.getSocketsInRoom('admin-panel');
console.log(`${sockets.length} admins online`);
// Broadcast to room
strapi.$io.server.to('premium-users').emit('exclusive-offer', data);Dashboard Widget:
- View real-time Socket.IO statistics directly on the Strapi admin dashboard
- Monitor active connections, rooms, and events per second
- Quick access to detailed monitoring page
Navigate to: Settings β Socket.IO
Configure:
- β CORS Origins - Allow your frontend domains
- β Role Permissions - Control who can connect and access content types
- β Security Settings - Enable authentication, rate limiting
- β Event Configuration - Customize event names, include relations
- β Redis Adapter - Scale across multiple servers
- β
Namespaces - Separate channels (e.g.,
/admin,/chat) - β Monitoring - View live connections and event logs
Enable content types in admin panel, then listen on frontend:
socket.on('article:create', (article) => {
console.log('New article:', article);
});
socket.on('article:update', (article) => {
console.log('Updated article:', article);
});
socket.on('article:delete', (article) => {
console.log('Deleted article ID:', article.id);
});Full TypeScript definitions are included:
import type { SocketIO, SocketIOConfig } from 'strapi-plugin-io/types';
const config: SocketIOConfig = {
contentTypes: ['api::article.article'],
socket: {
serverOptions: {
cors: { origin: '*' }
}
}
};The plugin includes a live statistics widget on your Strapi admin home page:
π Widget Features:
- π’ Live connection status with pulsing indicator
- π₯ Active connections count
- π¬ Active rooms count
- β‘ Events per second
- π Total events processed
- π Auto-updates every 5 seconds
See it in action: Navigate to your admin home page after installing the plugin!
For details, see WIDGET.md
π Complete Documentation:
- API Reference - Complete API documentation with TypeScript definitions
- Usage Guide - Practical examples & real-world use cases
- Widget Guide - Dashboard widget documentation
- Security Guide - Security best practices & implementation
- Features - Full feature list with examples
- Optimizations - Performance tuning & benchmarks
- β Real-Time Events - Automatic content type CRUD event broadcasting
- β Entity Subscriptions π - Subscribe to specific entities for targeted updates
- β Authentication - JWT and API Token support with role-based access
- β Admin Panel - Visual configuration for all settings
- β Room Management - Advanced room/channel system
- β
Namespaces - Separate communication channels (e.g.,
/admin,/chat) - β Monitoring - Live connection stats and event logs
- β Redis Adapter - Scale across multiple servers
- β Rate Limiting - Prevent abuse with configurable limits
- β Security - IP whitelisting, authentication requirements, input validation
- β TypeScript - Full type definitions for IntelliSense
- β Helper Functions - 12+ utility functions for common tasks
- β Performance - Optimized for production use
- β Vibecode Ready - IDE-friendly with comprehensive documentation
The plugin is optimized for production use:
- Intelligent Caching: Roles and permissions are cached for 5 minutes, reducing DB queries by up to 90%
- Debouncing: Bulk operations are debounced to prevent event flooding
- Parallel Processing: All emissions are processed in parallel for maximum throughput
- Connection Pooling: Supports 2500+ concurrent connections with optimized memory usage (~17KB per connection)
See OPTIMIZATIONS.md for detailed performance benchmarks and best practices.
Good News: The API remains 100% compatible! π
Most projects migrate in under 1 hour.
- Update Strapi to v5:
npm install @strapi/strapi@5 - Update plugin:
npm install strapi-plugin-io@latest - Test your application - configuration stays the same!
- β Package structure: Uses new Strapi v5 Plugin SDK
- β Dependencies: Updated to Strapi v5 peer dependencies
- β
Build process: Optimized build with
npm run build - β Configuration: Same as v2, no changes needed!
- β API: All methods work identically
π Complete Migration Guide: See docs/guide/migration.md or visit https://strapi-plugin-io.netlify.app/guide/migration
# Install dependencies
npm install
# Build the plugin
npm run build
# Watch for changes
npm run watch
# Verify plugin structure
npm run verifyFor more detailed documentation, visit: https://strapi-plugin-io.netlify.app/
If any bugs are found please report them as a Github Issue
Check out other useful Strapi v5 plugins by @Schero94:
π§ Magic-Mail
Enterprise email management with OAuth 2.0 - Perfect for sending notifications via Socket.IO events
π Magic-Sessionmanager
Advanced session tracking - Monitor Socket.IO connections and user activity
π Magicmark
Bookmark management - Share bookmarks in real-time with Socket.IO
MIT
Maintained by @ComfortablyCoding and @hrdunn
Updated and enhanced by @Schero94