Middleware (v1)
This documents the old v1 API. See Middleware for the current version.
Zocket middleware runs before a handler and can add derived values to ctx or block execution by throwing.
Signature
Section titled “Signature”const withExtras = zo.message.use(({ ctx, payload }) => { return { /* merged into ctx */ };});Authentication + context narrowing
Section titled “Authentication + context narrowing”const requireUser = zo.message.use(({ ctx }) => { if (!ctx.user) throw new Error("UNAUTHORIZED"); return { user: ctx.user };});Composing middleware
Section titled “Composing middleware”const requireAdmin = ({ ctx }) => { if (ctx.userRole !== "admin") throw new Error("FORBIDDEN"); return { isAdmin: true as const };};
const adminMessage = requireUser.use(requireAdmin);As of @zocket/core@0.1.0, thrown errors are not serialized back to the client. If middleware throws, the client call may reject due to RPC timeout.