GraphQL subscriptions with Apollo
Serve GraphQL subscriptions over AnyCable using standard Apollo tooling. With AnyCable Pro, the server speaks the graphql-ws protocol directly, so clients need no AnyCable-specific code: any Apollo-compatible client (web, React Native, Apollo Studio) connects to a dedicated GraphQL endpoint.
Configure the client
Point Apollo's WebSocket link at the AnyCable GraphQL endpoint:
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { createClient } from 'graphql-ws'
const wsLink = new GraphQLWsLink(createClient({
url: 'ws://localhost:8080/graphql'
}))This is the official Apollo WebSocket link configuration; see Apollo's guide for wiring the link into your ApolloClient (splitting subscription traffic from queries). The legacy subscriptions-transport-ws protocol is supported, too.
Authenticate
Pass credentials via connection params:
const wsLink = new GraphQLWsLink(createClient({
url: 'ws://localhost:8080/graphql',
connectionParams: {
token: 'some-token'
}
}))The server forwards them to your backend as a JSON-encoded x-apollo-connection HTTP header; see Apollo GraphQL support for the backend example.
With JWT identification, pass the token as the jid connection param or as a query parameter (ws://localhost:8080/graphql?jid=<token>).
Server requirements
- AnyCable Pro with the GraphQL endpoint enabled:
anycable-go --graphql_path=/graphql. - A backend with graphql-ruby and the graphql-anycable plugin. Your GraphQL Ruby code stays unchanged.
See Apollo GraphQL support for the full server configuration and a React Native demo.
Without Pro
With Rails and graphql-ruby, clients can also connect over the standard Action Cable protocol using graphql-ruby's ActionCableLink, passing a consumer created by the AnyCable JS SDK.