Real-Time Subscriptions with useSubscription
WebSocket link setup, useSubscription(), merging subscription data into reactive state.
Real-Time Subscriptions with useSubscription is a free Vue Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Real-Time With Subscriptions
GraphQL subscriptions push data from server to client over a persistent connection. Where queries pull once, subscriptions stream updates — perfect for chat, live feeds, and notifications.
WebSocket Transport
Subscriptions need a long-lived connection, so they use WebSockets instead of HTTP. The graphql-ws library provides the modern protocol via GraphQLWsLink.
npm install graphql-wsCreating the WebSocket Link
Wrap a graphql-ws client in a GraphQLWsLink pointing at the wss:// subscription endpoint.
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { createClient } from 'graphql-ws'
const wsLink = new GraphQLWsLink(createClient({
url: 'wss://api.example.com/graphql'
}))The Transport Problem
Queries and mutations should still go over HTTP, while subscriptions go over WebSocket. You cannot use one link for everything — you need to split traffic by operation type.
Splitting Links
The split function routes each operation: subscriptions to the WebSocket link, everything else to the HTTP link, based on the parsed operation definition.
import { split, HttpLink } from '@apollo/client/core'
import { getMainDefinition } from '@apollo/client/utilities'
const httpLink = new HttpLink({ uri: '/graphql' })
const link = split(
({ query }) => {
const def = getMainDefinition(query)
return def.kind === 'OperationDefinition' && def.operation === 'subscription'
},
wsLink,
httpLink
)Wiring the Split Link Into the Client
Pass the combined link to the Apollo client instead of a plain uri. Now the client knows how to route each operation.
const apolloClient = new ApolloClient({
link,
cache: new InMemoryCache()
})useSubscription Basics
The useSubscription composable opens the stream and returns reactive state. Like useQuery it gives result, loading, and error.
import { useSubscription } from '@vue/apollo-composable'
import { gql } from '@apollo/client/core'
const { result } = useSubscription(gql(
'subscription { messageAdded { id text } }'
))Handling Each Push
Use the onResult hook to react to every pushed event as it arrives — the natural place to handle streaming data.
const { onResult } = useSubscription(MESSAGE_ADDED)
onResult((res) => {
console.log('New message', res.data.messageAdded)
})Pushing Into a Reactive Array
A common pattern: keep a local reactive array and append each new event so the template renders a live, growing list.
const messages = ref([])
const { onResult } = useSubscription(MESSAGE_ADDED)
onResult((res) => {
messages.value.push(res.data.messageAdded)
})Subscription Variables
Subscriptions accept variables just like queries — for example, subscribe to messages for a single chat room.
useSubscription(
gql('subscription($room: ID!) { messageAdded(room: $room) { text } }'),
{ room: 'general' }
)Subscriptions vs Polling
Polling refetches a query on a timer; subscriptions push only when something changes. Subscriptions are more efficient for true real-time data, while polling is simpler when near-real-time is enough.
Quick Check
Test your knowledge of subscriptions.
Recap
You learned real-time subscriptions:
- Subscriptions push data over WebSockets via GraphQLWsLink (graphql-ws).
- Use split() to send subscriptions over WS and queries/mutations over HTTP.
- useSubscription returns reactive result with onResult for each push.
- Append pushed events to a reactive array for a live list.
Frequently asked questions
Is the “Real-Time Subscriptions with useSubscription” lesson free?
Yes — the full text of “Real-Time Subscriptions with useSubscription” is free to read here on the web, and the Vue Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.
What will I learn in “Real-Time Subscriptions with useSubscription”?
WebSocket link setup, useSubscription(), merging subscription data into reactive state. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vue Academy?
No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Real-Time Subscriptions with useSubscription” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vue Academy lesson?
Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Apollo Client Setup in Vue 3
- useQuery for Data Fetching
- useMutation for Data Changes
- Real-Time Subscriptions with useSubscription