This course is no longer maintained and may be out-of-date. While it remains available for reference, its content may not reflect the latest updates, best practices, or supported features.
Subscription
When we had initially set up Apollo, wired up an HttpLink
to be able to make queries and mutations. But subscriptions is an advanced usecase, so we have to install more dependencies to set up subscriptions:
npm install subscriptions-transport-ws --save
Now we need to update our ApolloClient
instance to point to the subscription server.
Open src/apollo-client.ts
and update the following imports:
- import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client/core"+ import { ApolloClient, split, InMemoryCache, HttpLink } from "@apollo/client/core"+ import { WebSocketLink } from "@apollo/client/link/ws"import { getMainDefinition } from "@apollo/client/utilities"import { onError } from "@apollo/client/link/error"import { logErrorMessages } from "@vue/apollo-util"function getHeaders() {const headers = {}const token = window.localStorage.getItem("apollo-token")if (token) {headers["Authorization"] = `Bearer ${token}`}return headers}// Create an http link:const httpLink = new HttpLink({uri: "https://hasura.io/learn/graphql",fetch: (uri: RequestInfo, options: RequestInit) => {options.headers = getHeaders()return fetch(uri, options)},})+ // Create a WebSocket link:+ const wsLink = new WebSocketLink({+ uri: "wss://hasura.io/learn/graphql",+ options: {+ reconnect: true,+ lazy: true,+ timeout: 30000,+ inactivityTimeout: 30000,+ connectionParams: () => {+ return { headers: getHeaders() }+ },+ },+ })const errorLink = onError((error) => {if (process.env.NODE_ENV !== "production") {logErrorMessages(error)}})// Create the apollo clientexport const apolloClient = new ApolloClient({cache: new InMemoryCache(),- link: errorLink.concat(httpLink),+ link: errorLink.concat(+ split(+ // split based on operation type+ ({ query }) => {+ const definition = getMainDefinition(query)+ return (+ definition.kind === "OperationDefinition" &&+ definition.operation === "subscription"+ )+ },+ wsLink,+ httpLink+ )+ ),})
Did you find this page helpful?
Start with GraphQL on Hasura for Free
Build apps and APIs 10x faster
Built-in authorization and caching
8x more performant than hand-rolled APIs

