Skip to content

Plugin configuration ​

The plugin reads config/plugins.js (or .ts) once at startup. Everything an editor may change at runtime lives in the admin settings instead, see Admin settings.

js
// config/plugins.js
module.exports = ({ env }) => ({
  io: {
    enabled: true,
    config: {
      contentTypes: ['api::article.article'],
      sensitiveFields: [],
      events: [],
      hooks: {},
      socket: { serverOptions: {} },
    },
  },
});

The config is validated at startup. An unknown shape (for example a handler that is not a function) stops Strapi with a validation error.

Options ​

OptionTypeDefaultDescription
contentTypesArray<string | ContentTypeConfig>[]Content types whose changes are sent. More can be added in the admin settings.
sensitiveFieldsstring[][]Extra field names that are never sent, on top of the built-in list.
eventsArray<{ name, handler, admin? }>[]Handlers for events your clients send. See Custom events.
hooks.init({ strapi, $io, io }) => void | PromisenoneRuns once during bootstrap, before the handshake. See Hooks.
socket.serverOptionsSocket.IO ServerOptions{}Passed to new Server(). Values set here win over the plugin defaults and the admin settings.

contentTypes ​

A string watches every action. An object narrows the actions or adds relations.

js
contentTypes: [
  'api::article.article',
  { uid: 'api::page.page', actions: ['publish', 'unpublish', 'delete'] },
  { uid: 'api::product.product', populate: ['category', 'images'] },
],
KeyTypeDefaultDescription
uidstringrequiredContent type uid, e.g. api::article.article.
actionsArray<'create' | 'update' | 'delete' | 'publish' | 'unpublish' | 'discardDraft'>all sixActions that send an event.
populate'*' | true | string[] | objectnoneRelations to load before create, update, publish and discardDraft are sent. '*' and true load one level of every relation. An object uses Strapi's populate syntax.

Events are named <singularName>:<action>, for example article:publish. Content types set here appear as read-only rows in the admin settings.

Payloads ​

ActionPayload
create, update, publish, discardDraft{ data: { id, attributes }, meta: {} }
unpublish, delete{ data: { documentId, locale? } }

Each role and API token receives the entry sanitized with its own Content API permissions. Populated relations it cannot read are removed. Keep populate small: every relation is loaded once per event and sanitized once per listening role or token.

sensitiveFields ​

Field names removed from every content event and from strapi.$io.raw() payloads, at any depth. The built-in list already covers password, resetPasswordToken, confirmationToken, apiKey, secret and similar keys, as well as fields marked private in the schema.

js
sensitiveFields: ['internalNotes', 'costPrice'],

Editors can add more under Settings > Socket.IO > Content events > Excluded fields.

events ​

js
events: [
  { name: 'connection', handler: ({ strapi }, socket) => strapi.log.debug(`[io] ${socket.id} connected`) },
  { name: 'ping', handler: (_ctx, socket, ...args) => args.at(-1)?.('pong') },
],
KeyTypeDescription
namestringClient event name. connection runs once per new socket.
handler({ strapi, io }, socket, ...args) => unknownio is strapi.$io. Errors are caught and logged.
adminbooleanAlso run on admin presence sockets. Default false.

Check socket.data.kind (public, user, token or admin) before you use an id. Full guide: Custom events.

hooks.init ​

js
hooks: {
  async init({ strapi, $io }) {
    $io.server.use((socket, next) => next());
  },
},
  • Awaited during bootstrap. The HTTP server is not listening yet.
  • Middleware added with $io.server.use() runs before the plugin handshake.
  • $io and io are the same object (io is kept for configs written for older versions).
  • An error is logged as [io] hooks.init failed and Strapi keeps starting.

An adapter attached here is detected like socket.adapter. More: Hooks.

socket.serverOptions ​

Passed to Socket.IO's new Server(httpServer, options). The plugin sets these defaults; anything you set wins.

OptionPlugin defaultWhy
destroyUpgradefalseOther WebSocket upgrades on Strapi's server (Data Transfer) are left to Strapi instead of being closed.
maxHttpBufferSize1e5 (100 KB)Caps the size of a client message. Socket.IO's own default is 1 MB.
corsfrom Allowed originsCORS headers for listed origins only.
allowRequestfrom Allowed originsRefuses polling and WebSocket requests from browser origins that are not allowed.
pingInterval, pingTimeout, connectTimeoutfrom the admin settingsApplied to new connections without a restart.

Setting cors or allowRequest yourself turns off the admin setting Allowed origins for that option.

js
socket: {
  serverOptions: {
    path: '/realtime', // clients then connect with io(url, { path: '/realtime' })
    maxHttpBufferSize: 1e6,
  },
},

Admin settings ​

Settings > Socket.IO > Settings. Changes apply to new connections without a restart. Stored in Strapi's plugin store and validated with a strict schema.

SettingDefaultDescription
Allowed originsnoneBrowser origins that may connect. With an empty list only the Strapi host itself and the origins of server.url / admin.url are allowed. Clients without an Origin header (servers, mobile apps) are always allowed.
Maximum connections0 (no limit)Refuses new connections above this number.
Ping interval / timeout25000 / 20000 msSocket.IO heartbeat.
Connection timeout45000 msTime a client has to finish the handshake.
Require authenticationoffRefuse clients without a JWT or API token.
Limit client eventsoff, 10/sPer-client event limit.
Allowed / blocked IPsnoneIPv4/IPv6 addresses and CIDR blocks. The client IP follows Strapi's server.proxy settings.
Only published contentonDo not send draft versions.
Excluded fieldsnoneField names never sent.
Content types and actionsnoneWatch more API content types without a deploy.
Roles: allow connectionall allowedRefuse sockets of a Users & Permissions role. What a role receives follows its permissions.
Entry subscriptions, limitoff, 100Let clients follow single entries with subscribe-entity (1 to 1,000 per client). Needs read permission of the client's role or token.
Show who is editing / typingon / onLive presence in the Content Manager.
Log connectionsoffInfo log line per connect and disconnect (no IPs or tokens).
Event log, sizeoff, 100In-memory list of recent events for Monitoring.

The section Export and import downloads the saved settings as JSON (no secrets) and imports such a file: the server checks it with the same schema (POST /io/settings/validate, needs Update settings), the changed values are listed for confirmation and fill the form, and nothing is stored until Save.

Environment variables ​

The plugin reads none itself. Use Strapi's env() helper in your config:

js
module.exports = ({ env }) => ({
  io: {
    enabled: env.bool('IO_ENABLED', true),
    config: {
      contentTypes: ['api::article.article'],
      socket: { serverOptions: { path: env('IO_PATH', '/socket.io') } },
    },
  },
});

See also ​

socket.adapter ​

Multi-server adapter for several processes (Railway replicas, pm2 cluster). The packages are optional peer dependencies.

ValueAdapter
'postgres' or { type: 'postgres' }@socket.io/postgres-adapter + pg, own pool (poolMax, default 2)
'redis' or { type: 'redis', url }@socket.io/redis-adapter + ioredis (url defaults to REDIS_URL)
async ({ strapi }) => adapterAny adapter; return { adapter, close } to have the plugin close your clients

Postgres options: connectionString, connection, poolMax, tableName, channelPrefix, payloadThreshold, cleanupInterval, heartbeatInterval, heartbeatTimeout. Redis options: url, redisOptions, key, requestsTimeout, publishOnSpecificResponseChannel (default true).

socket.websocketOnly ​

true sets transports: ['websocket'] unless socket.serverOptions.transports is set. Needed without sticky sessions.

cluster ​

KeyDefaultMeaning
enabled'auto'On with a multi-server adapter, in pm2 cluster mode or on Railway.
pollInterval3000ms between reads of control signals (settings, revocations, cache, reset).
heartbeatInterval10000ms between heartbeats (monitoring totals, connection cap, peer detection).

Guide: Running several instances.

Released under the MIT License. Updated and made better by @Schero94 · llms.txt