Stream Live Data From One Server

GraphQL subscriptions with Apollo Server and Apollo Client for web


Choose this path when you want live, server-driven updates in a web UI—for example activity feeds, dashboards, or collaboration—and you have (or plan) a single GraphQL endpoint backed by Apollo Server. You add GraphQL subscription fields, expose them over a WebSocket with the recommended protocol, and receive events in Apollo Client with React.

Prerequisites

  • An existing Node.js GraphQL server using Apollo Server (or a local project where you can add it)

  • A React web app where you can install Apollo Client, or a plan to create one alongside your server

By the end of this guide, you'll have:

  • A Subscription field in your schema with a resolver that emits events

  • A WebSocket endpoint that speaks the graphql-transport-ws subprotocol (via graphql-ws)

  • Apollo Client configured with a split link: HTTP for queries and mutations, WebSocket for subscriptions

  • A React component that uses useSubscription to render live payload data

Steps to complete

1. Define subscriptions on Apollo Server

Add a subscription root field to your schema and implement it with an async iterator (for example using an in-memory PubSub for development).

Follow Subscriptions in Apollo Server for schema syntax, resolver shape, and how to publish events from mutations or other server logic.

2. Attach a WebSocket server for subscription traffic

Apollo Server serves queries and mutations over HTTP. Subscriptions use a separate WebSocket server that uses the same schema and executes subscription operations.

Use the setup from the Apollo Server documentation to:

  • Install and configure graphql-ws

  • Create a WebSocket server on a URL your clients can reach (often a dedicated path such as /graphql on the same host, with a WebSocket URL like ws://localhost:4000/graphql)

Complete the Getting started and Enabling subscriptions sections in Subscriptions in Apollo Server before you move on to the client.

Install @apollo/client and graphql-ws in your React app. Point an HttpLink at your HTTP GraphQL endpoint and a GraphQLWsLink at your WebSocket URL. Combine them with split from @apollo/client/link/core so subscription operations use WebSocket and everything else uses HTTP.

Follow Subscriptions in Apollo Client (React), including the WebSocket setup section, for the exact ApolloClient constructor pattern and link chain.

4. Run a subscription from React

Define a subscription document with the gql tag, wrap your app with ApolloProvider, and call useSubscription in a component. Handle loading, data, and error the same way you do for queries.

See The useSubscription hook for usage details and options.

note
When you use a federated supergraph in Apollo GraphOS, follow Stream live data through GraphOS instead: clients use subscriptions over HTTP (multipart) to the router, not a WebSocket directly to one server.

Resources

Feedback