SubscriptionOnStart handler is a custom module hook that allows you to intercept and customize the initialization of GraphQL subscriptions.
This handler is called once when a subscription starts, giving you the opportunity to validate permissions, send initial events, or perform setup logic.
This handler is particularly useful for:
- Subscription authentication: Validate JWT tokens or user permissions before allowing subscriptions
- Initial event delivery: Send welcome messages or current state to new subscribers
- Subscription logging: Track subscription attempts and user behavior
- Connection validation: Ensure clients meet specific criteria before subscribing
- Rate limiting: Control subscription attempts per user or client
- State initialization: Initialize state used by other handlers such as
OnReceiveEventsorOnPublishEventsof the same module
Handler Interface
In order to use theSubscriptionOnStart handler you need to create a Custom Module which implements the SubscriptionOnStartHandler interface.
Error Handling
When you return an error from theSubscriptionOnStart handler, the router responds to the client with an error event and closes the subscription.
You can choose to log a generic error or a custom error response with more details for the client.
Usage Example
Complete Custom Module with Event Bypass
The following example demonstrates how to register a passiveSubscriptionOnStart handler that logs subscription attempts but allows all subscriptions to proceed normally.
Return initial events
You can usectx.EmitLocalEvent() to send initial or welcome events to subscribers immediately when they connect.
This is useful for providing current state or welcome messages.
It has to be a valid JSON object that contains the
__typename field to identify the entity type we want to return
for this subscription. The other field in this case is id, which represents the entity key of Employee types as defined in the schema.
The router will use this information to resolve all fields requested by the subscriber to generate a complete response.