DocumentationCore Protocol

Middleware

Express-style middleware pipeline. Two types: connection middleware (runs on connect) and message middleware (runs on every message).

Connection Middleware

// Global — runs for all connections
server.use((socket, next) => {
  console.log("New connection:", socket.id);
  next(); // Allow connection
});

// Auth middleware
server.use(async (socket, next) => {
  const token = getToken(socket);
  if (!token) return next(new Error("No token"));

  try {
    const user = await verifyToken(token);
    (socket as any).user = user;
    next();
  } catch {
    next(new Error("Invalid token"));
  }
});

// Namespace-specific middleware
const admin = server.of("/admin");
admin.use((socket, next) => {
  if ((socket as any).user?.role === "admin") next();
  else next(new Error("Admin access required"));
});

Message Middleware

// Global message middleware — rate limiting, logging, etc.
server.useMessage((socket, message, next) => {
  console.log(`[${socket.id}] ${message.type}`);
  next();
});

// Namespace-specific message middleware
admin.useMessage((socket, message, next) => {
  if (message.type.startsWith("admin:")) next();
  else next(new Error("Invalid message type for admin"));
});

If any middleware calls next(error), the connection is rejected or the message is dropped, and the client receives a __pp_error event.

Next: Acknowledgements