The function to create a context for subscriptions includes `connection`, while the function for Queries and Mutations contains the arguments for the integration, in express's case `req` and `res`. This means that the context creation function needs to check the input. This is especially important, since the auth tokens are handled differently depending on the transport:
```js
const server = new ApolloServer({
schema,
context: async ({ req, connection }) => {
if (connection) {
// check connection for metadata
return {};
} else {
// check from req
const token = req.headers.authorization || "";
return { token };
}
},
});
```
As you can see Apollo Server 2.0 allows realtime data without invasive changes to existing code.
For a full working example please have a look to [this repo](https://github.com/daniele-zurico/apollo2-subscriptions-how-to) provided by [Daniele Zurico](https://github.com/daniele-zurico/apollo2-subscriptions-how-to)
Sometimes a client will want filter out specific events based on context and arguments.
To do so, we can use `withFilter` helper from this package, which wraps `AsyncIterator` with a filter function, and let you control each publication for each user.
Let's see an example - for the `commentAdded` server-side subscription, the client want to subscribe only to comments added to a specific repo:
```
subscription($repoName: String!){
commentAdded(repoFullName: $repoName) {
id
content
}
}
```
When using `withFilter`, provide a filter function, which executed with the payload (the published value), variables, context and operation info, and it must return boolean or Promise<boolean> indicating if the payload should pass to the subscriber.
Here is the following definition of the subscription resolver, with `withFilter` that will filter out all of the `commentAdded` events that are not the requested repository:
The subscription lifecycle hooks to create an authenticated transport by using `onConnect` to validate the connection.
`SubscriptionsClient` supports `connectionParams` ([example available here](../react/advanced/subscriptions.html#authentication)) that will be sent with the first WebSocket message. All GraphQL subscriptions are delayed until the connection has been fully authenticated and your `onConnect` callback returns a truthy value.
`connectionParams` in the `onConnect` callback provide the ability to validate user credentials.
The GraphQL context can also be extended with the authenticated user data.
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});
```
The example above validates the user's token that is sent with the first initialization message on the transport, then it looks up the user and returns the user object as a Promise. The user object found will be available as `context.currentUser` in your GraphQL resolvers.
In case of an authentication error, the Promise will be rejected, and the client's connection will be rejected as well.
With an existing HTTP server (created with `createServer`), we can add subscriptions using the `installSubscriptionHandlers`. Additionally, the subscription-capable integrations export `PubSub` and other subscription functionality.
console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
})
```
## Lifecycle Events
`ApolloServer` exposes lifecycle hooks you can use to manage subscriptions and clients:
*`onConnect` - called upon client connection, with the `connectionParams` passed to `SubscriptionsClient` - you can return a Promise and reject the connection by throwing an exception. The resolved return value will be appended to the GraphQL `context` of your subscriptions.
*`onDisconnect` - called when the client disconnects.