0
0
GraphQLquery~5 mins

WebSocket transport in GraphQL

Choose your learning style9 modes available
Introduction

WebSocket transport lets your app keep a live connection to the server. This helps send and get data instantly without asking again and again.

You want to get live updates like chat messages or notifications.
You need to show real-time data like stock prices or sports scores.
Your app should react quickly when data changes on the server.
You want to reduce delays by avoiding repeated requests.
You want to keep a smooth connection for interactive apps.
Syntax
GraphQL
subscription {
  newMessage {
    id
    content
    sender
  }
}
This example shows a GraphQL subscription using WebSocket transport.
Subscriptions keep the connection open to receive updates automatically.
Examples
Listen for changes in user online status in real time.
GraphQL
subscription {
  userStatusChanged {
    userId
    online
  }
}
Get live updates for Apple stock price.
GraphQL
subscription {
  stockPriceUpdated(symbol: "AAPL") {
    price
    time
  }
}
Receive new messages instantly in a specific chat room.
GraphQL
subscription {
  chatRoomMessages(roomId: "123") {
    id
    text
    sender
  }
}
Sample Program

This subscription listens for new notifications sent by the server. When a new notification arrives, the server pushes it immediately through the WebSocket connection.

GraphQL
subscription {
  newNotification {
    id
    message
    createdAt
  }
}
OutputSuccess
Important Notes

WebSocket transport is mainly used with GraphQL subscriptions.

It keeps the connection open, so the server can send data anytime.

Make sure your server supports WebSocket for subscriptions to work.

Summary

WebSocket transport keeps a live connection for real-time data.

Use it with GraphQL subscriptions to get instant updates.

It is great for chat apps, notifications, and live feeds.