PubSubJS
Use this skill when implementing or reviewing code that uses PubSubJS. Prefer the documented APIs and patterns below, and keep examples aligned with the current library behavior.
When to Apply
- •Defining event schemas and types
- •Publishing or subscribing to events
- •Adding attributes for filtering
- •Setting up transports (WebSocket, Redis, SSE)
- •Using the React hooks package
Core Patterns
Define Events
typescript
import { z } from "zod";
import { defineEvent } from "@pubsubjs/core";
export const events = defineEvent([
{
name: "user.created",
schema: z.object({
userId: z.string(),
email: z.string().email(),
}),
attributesSchema: z.object({
userId: z.string(),
region: z.string(),
}),
},
]);
Publish
typescript
const publisher = new Publisher({ events, transport });
await publisher.publish("user.created", payload, {
attributes: { userId: "u1", region: "eu" },
});
Subscribe (with filter)
typescript
const subscriber = new Subscriber({ events, transport });
subscriber.on(
"user.created",
(payload) => {
console.log(payload.email);
},
{
filter: {
region: "eu",
},
}
);
await subscriber.subscribe();
Attributes & Filtering
Filters accept operators: $in, $exists, $prefix, $ne, $gt, $gte, $lt, $lte, $between.
- •Multiple keys are AND
- •Multiple conditions on the same key are OR
- •Dot notation is supported for nested attributes (
"user.id")
Transports
WebSocket
- •
WebSocketServerTransportfor servers (Bun.serve) - •
WebSocketClientTransportfor browsers/clients
Redis
- •
RedisTransportfor distributed systems (URL + optional channel prefix)
SSE
- •
SSEClientTransportis client-only - •SSE servers can be implemented outside PubSubJS
React Hooks
createPubSub returns hooks, no provider required.
typescript
const { useSubscribe, usePublish } = createPubSub({ events, transport });
useSubscribe("user.created", handler, []);
const { publish } = usePublish();
Notes
- •Use Bun for scripts and builds when applicable
- •Keep examples consistent with the current docs at https://pubsubjs.shkumbinhsn.com/