GraphQL Subscriptions
GraphQL subscriptions enable real-time communication by allowing clients to receive updates from the server when specific events occur. Unlike queries and mutations, which are one-time operations, subscriptions keep a connection open and push data as it changes.
What Are Subscriptions?
- They are a way to subscribe to specific events or changes.
- Typically implemented over WebSockets.
- Clients receive live updates without polling.
Basic Subscription Syntax
This subscription listens for new messages and returns the specified fields whenever a new message is created.
How Subscriptions Work
- The client initiates a subscription request.
- The server establishes a persistent connection (usually WebSocket).
- When the subscribed event occurs, the server pushes data to the client.
- The client updates the UI or handles the data accordingly.
Defining Subscription Types in Schema
The Subscription
type is a root type like Query
and Mutation
.
Example: Using Subscriptions with Apollo Server
const { PubSub } = require("graphql-subscriptions");
const pubsub = new PubSub();
const resolvers = {
Subscription: {
newMessage: {
subscribe: () => pubsub.asyncIterator(["NEW_MESSAGE"]),
},
},
Mutation: {
sendMessage: (_, { content, author }) => {
const message = { id: generateId(), content, author };
pubsub.publish("NEW_MESSAGE", { newMessage: message });
return message;
},
},
};
Client-side Usage Example (Apollo Client)
import { useSubscription, gql } from "@apollo/client";
const NEW_MESSAGE_SUBSCRIPTION = gql`
subscription {
newMessage {
id
content
author {
name
}
}
}
`;
function Messages() {
const { data, loading } = useSubscription(NEW_MESSAGE_SUBSCRIPTION);
if (loading) return <p>Loading...</p>;
return <div>{data.newMessage.content}</div>;
}
Use Cases for Subscriptions
- Chat applications
- Live sports scores
- Real-time notifications
- Collaborative document editing
- Stock price updates
Important Considerations
- Subscriptions require a persistent connection (WebSocket or similar).
- More complex infrastructure than queries/mutations.
- Consider security and authorization carefully.
- Not all GraphQL servers support subscriptions natively.
Tools & Libraries
- Apollo Server & Client
- graphql-ws — modern WebSocket protocol for GraphQL
- Subscriptions-Transport-WS (deprecated but still in use)
- Hasura — real-time GraphQL engine
Summary
- Subscriptions bring real-time capabilities to GraphQL APIs.
- They use persistent connections to push data on events.
- Ideal for live updates in modern applications.