What is WebSocket in GraphQL: Explanation and Example
GraphQL, WebSocket is a communication protocol used to keep a live connection open between client and server for real-time data updates. It enables GraphQL subscriptions, allowing clients to receive data instantly when changes happen without repeatedly asking the server.How It Works
Imagine you are chatting with a friend. Instead of calling them every minute to ask if they have a new message, you keep the phone line open so they can tell you immediately when they have something to say. This is how WebSocket works in GraphQL.
Normally, GraphQL queries and mutations happen over HTTP, which means the client asks for data and the server responds once. But with WebSocket, the client opens a continuous connection to the server. This connection stays open, so the server can send new data instantly whenever it changes.
This live connection is mainly used for GraphQL subscriptions. Subscriptions let clients listen for specific events or data changes, like new chat messages or live scores, and get updates automatically without asking again.
Example
This example shows a simple GraphQL subscription using WebSocket to get live updates when a new message is added.
import { createClient } from 'graphql-ws'; const client = createClient({ url: 'ws://localhost:4000/graphql', }); const subscribeToMessages = () => { client.subscribe( { query: `subscription { newMessage { id content author } }`, }, { next: (data) => { console.log('New message received:', data.data.newMessage); }, error: (err) => console.error(err), complete: () => console.log('Subscription ended'), } ); }; subscribeToMessages();
When to Use
Use WebSocket in GraphQL when you need real-time updates without the client constantly asking the server for new data. This is perfect for chat apps, live sports scores, stock price updates, or collaborative tools where data changes frequently.
It improves user experience by delivering instant updates and reduces server load by avoiding repeated requests. However, it requires a server and client setup that supports WebSocket connections.
Key Points
- WebSocket keeps a live connection open for continuous data flow.
- It enables GraphQL subscriptions for real-time updates.
- Ideal for apps needing instant data like chats or live feeds.
- Reduces repeated requests and improves efficiency.
- Requires both client and server to support WebSocket protocol.