What are Subscriptions in GraphQL?
In GraphQL, subscriptions are a powerful feature that allows clients to receive real-time updates from the server. Unlike queries and mutations, which are one-time requests, subscriptions enable clients to listen for specific events and automatically receive updates whenever the data changes. This is particularly useful for applications that require live data, such as chat applications, notifications, or dashboards.
Key Features of GraphQL Subscriptions
- Real-Time Updates: Subscriptions allow clients to receive immediate updates when data changes on the server, providing a dynamic user experience.
- Event-Driven: Subscriptions are based on events, meaning that clients can subscribe to specific events and react accordingly when those events occur.
- Single Endpoint: Like queries and mutations, subscriptions are typically handled through a single endpoint, making it easy to manage real-time communication.
- Strongly Typed: Subscriptions are defined in the GraphQL schema, ensuring that clients receive the expected data structure.
Basic Structure of a Subscription
A GraphQL subscription starts with the subscription
keyword, followed by the event you want to listen to. Here’s a simple example of a subscription that listens for new users being created:
subscription {
userCreated {
id
name
email
}
}
Sample Subscription Explained
In the example above, the subscription userCreated
is defined to listen for new users. When a new user is created on the server, the client will receive the id
, name
, and email
fields of the newly created user in real-time.
Sample Response
When a new user is created, the server might send a response like this to all subscribed clients:
{
"data": {
"userCreated": {
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
}
}
Setting Up Subscriptions
To implement subscriptions in a GraphQL server, you typically use a WebSocket connection. This allows the server to push updates to clients. Below is a basic example of how to set up a subscription in a GraphQL server using Apollo Server:
const { ApolloServer, gql, PubSub } = require('apollo-server');
const pubsub = new PubSub();
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User ]
}
type Mutation {
createUser (name: String!, email: String!): User
}
type Subscription {
userCreated: User
}
`;
const resolvers = {
Query: {
users: () => {
// Fetch users from the database
},
},
Mutation: {
create:User (parent, { name, email }) => {
const newUser = { id: "1", name, email }; // Simulate user creation
pubsub.publish('USER_CREATED', { userCreated: newUser });
return newUser ;
},
},
Subscription: {
userCreated: {
subscribe: () => pubsub.asyncIterator(['USER_CREATED']),
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Conclusion
Subscriptions in GraphQL provide a powerful way to enable real-time communication between clients and servers. By allowing clients to listen for specific events, subscriptions enhance the interactivity of applications and ensure that users receive timely updates. Understanding how to implement and use subscriptions is essential for building modern, responsive applications that require live data.