Middleware & Plugins
Intercept events with middleware and extend PlayMesh with reusable plugins.
Middleware
Middleware functions intercept every incoming client event before it reaches instance handlers. They follow the
(context, next) pattern.Signature
Logging
Rate limiting (built in)
PlayMesh ships a
rateLimit middleware with per-session, per-event token buckets. '*' catches events without their own limit; over-limit events are rejected with a RATE_LIMITED error the client sees via onError.onExceed: 'warn' (default, error to the client), 'drop' (silent) or 'kick' (warn, then kick with code RATE_LIMITED after strikes violations - default 3 - without a quiet strikeWindowMs, default 10s). Every limited event is counted in mesh.metrics().errors.Role-based access (built in)
requireRole protects events by role - a session needs at least one of the listed roles (granted by your authenticate hook or session.setRoles()). Events without a rule stay open. Denied events reach the client via onError with code ROLE_REQUIRED. Roles changed live apply to the next event.Custom authorization
✦
Don't write a catch-all middleware to handle lobby events (shop, wardrobe, game selection) from any room - register them with
mesh.on(event, handler), which receives events from any session, even one in no instance.⚠
Calling
next()multiple times in the same middleware throws a "next() called multiple times" error.Plugins
Plugins are objects with an
install(mesh) method. They receive the PlayMesh instance and can register hooks, middleware, domains, and anything else.Plugin interface
Writing a plugin
Using a plugin
✦
Plugins are installed before bootstrap hooks run, so a plugin can safely register its own bootstrap hooks.