Skip to content

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.

const withExtras = zo.message.use(({ ctx, payload }) => {
return { /* merged into ctx */ };
});
const requireUser = zo.message.use(({ ctx }) => {
if (!ctx.user) throw new Error("UNAUTHORIZED");
return { user: ctx.user };
});
const requireAdmin = ({ ctx }) => {
if (ctx.userRole !== "admin") throw new Error("FORBIDDEN");
return { isAdmin: true as const };
};
const adminMessage = requireUser.use(requireAdmin);

As of @zocket/[email protected], thrown errors are not serialized back to the client. If middleware throws, the client call may reject due to RPC timeout.