# Subscriptions: Getting Started
Subscriptions allow GraphQL clients to observe specific events and receive updates from the server when those events occur.
NOTE
Much of the credit should be given to the Ruby implementation (opens new window) as they provided a great overview of how the backend should work.
# Setup
Add the service provider to your config/app.php
:
'providers' => [
\Nuwave\Lighthouse\Subscriptions\SubscriptionServiceProvider::class,
],
If you want to use the Pusher driver, you need to install the Pusher PHP Library (opens new window) for interacting with the Pusher HTTP API.
composer require pusher/pusher-php-server
If you want to use the Laravel Echo driver, you need to set the env LIGHTHOUSE_BROADCASTER=echo
.
# Subscriptions Versions
Lighthouse returns the subscription channel as part of the response under extensions
.
You can configure which format is used with subscriptions.version
in lighthouse.php
.
For new applications, version 2 is recommended. When upgrading, make sure
your clients no longer depend on the redundant channels
key from version 1.
Version 2 (Recommended)
{
"data": {...},
"extensions": {
"lighthouse_subscriptions": {
"version": 2,
"channel": "channel-name"
}
}
}
Version 1 (Legacy)
{
"data": {...},
"extensions": {
"lighthouse_subscriptions": {
"version": 1,
"channel": "channel-name",
"channels": {
"subscriptionName": "channel-name"
}
}
}
}
# Empty Response Optimization
Lighthouse returns the subscription channel as part of the response under extensions
.
If subscriptions.exclude_empty
in lighthouse.php
is set to true
,
API responses without a subscription channel will not contain lighthouse_subscriptions
in extensions
.
This optimizes performance by sending less data, but clients must anticipate this appropriately.
# Expiring Subscriptions
Subscriptions do not expire by themselves. Unless you delete a subscription, it will continue to broadcast events after the client has disconnected.
The easiest way to expire subscriptions automatically is to use the env LIGHTHOUSE_SUBSCRIPTION_STORAGE_TTL
to set an expiration time in seconds (e.g. LIGHTHOUSE_SUBSCRIPTION_STORAGE_TTL=3600
to expire in one hour).
# Pusher Expiration Webhook
If you are using the Pusher driver, you can use a channel existence
(opens new window) webhook to mitigate this problem.
When a Pusher channel is vacated (i.e. there are no subscribers), it will trigger the webhook,
which will instruct Lighthouse to delete the subscription.
The webhook URL will typically be:
/graphql/subscriptions/webhook
You can add the webhook in the Pusher Dashboard. Select the type channel existence
.