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. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, and your progress syncs across the web and the CoddyKit app. The Vue Academy course includes 4 lessons in total.
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.
Learn HTML with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 42
- Lessons
- 156
Frequently Asked Questions
Is the “Real-Time Subscriptions with useSubscription” lesson free?
Yes — any 3 lessons of the Vue Academy learning path, including “Real-Time Subscriptions with useSubscription”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Vue Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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