Implement a React application with GraphQL subscriptions for live updates.
- User
Implement a React application with GraphQL subscriptions for live updates.
Assistant
Considering Tech Choices
I've been mapping out the best technology choices for this live-updating React application. Apollo Client seems like the frontrunner for GraphQL interactions, given its robust support for subscriptions. I'm also thinking through the best way to structure the React components for optimal data flow and minimal re-renders. This requires careful consideration.
Building the GraphQL Backend
I'm now fully immersed in constructing the GraphQL backend using Apollo Server. The essential pieces are falling into place: type definitions for subscriptions (specifically a "New Comment" scenario), a resolver to publish events, and a PubSub mechanism. I'm focusing on the "Hello World" of subscriptions - a simple "New Comment" feed. I've installed the necessary npm packages and am deep in schema and resolver code. Next up: Getting the subscriptions to actually work!
Refining Backend Structure
I'm presently refactoring the GraphQL backend to align with best practices and v4 standards. I'm focusing on type definitions: Queries fetching comments, Mutations posting comments, and Subscriptions for new comment notifications. Resolvers use
PubSubfor event broadcasting. The server now integratesmakeExecutableSchema,WebSocketServer,useServer(fromgraphql-ws), and the newerApolloServer. I'm also addressing the somewhat complex v4 setup for separating HTTP and WebSocket servers.Optimizing Component Logic
I'm currently focused on component structure and how to handle different operation types efficiently. I'm exploring the nuances of
useSubscriptionversussubscribeToMorein React components. ConsideringLatestCommentusing subscription andCommentListusing query to highlight the different approach. I'm aiming for a live comment feed, which is ideal for a tutorial. This design uses a dedicatedLiveCommentscomponent with an input field (mutation) and a list (subscription) for clarity. I'm now implementing the GraphQL schema, including queries, mutations, and subscriptions withgql, along with properLinksetup.Confirming Server Configuration
I'm verifying that the Apollo Server v4 setup with WebSockets is correct. It's crucial to have the
httpserver, attachWebSocketServer, and utilize the cleanup callback inApolloServerplugins. I'm also confirming that the WebSocket URL usesws://and the HTTP URL useshttp://. I'm going with simpleuseSubscriptionapproach for simplicity. I'll make sure the live data is working correctly with the backend, and then implement the full cache update withsubscribeToMorefor the second live view.Defining List Rendering
I've decided to implement a component that renders a list of messages using
useSubscription. This aligns better with the common "real-time list" use case that users often request.Documenting the Links
I'm focusing now on adding thorough comments to explain the link splitting logic in
App.js, especially thegetMainDefinitionfunction and how it distinguishes subscription operations. I want to highlight the critical role ofgraphql-wsfor WebSocket connections and the overall structure, ensuring all of this clearly communicates why we're doing this.This is a complete, step-by-step guide to implementing GraphQL Subscriptions using React, Apollo Client, and Apollo Server.
Since Subscriptions require a WebSocket backend to function, I will provide the code for both the Server and the Client.
Prerequisites
- Node.js installed.
- Two separate terminal windows (one for server, one for client).
Part 1: The GraphQL Backend (Apollo Server)
First, we need a server capable of handling WebSockets. We will build a simple "Message Board".
-
Create a folder and initialize the project:
mkdir graphql-subs-demo cd graphql-subs-demo mkdir server cd server npm init -y -
Install dependencies: Note: Apollo Server v4 requires a specific setup for WebSockets using
graphql-ws.npm install @apollo/server graphql graphql-ws ws cors express body-parser graphql-subscriptions -
Create
index.jsinside the server folder:// server/index.js const { ApolloServer } = require('@apollo/server'); const { expressMiddleware } = require('@apollo/server/express4'); const { createServer } = require('http'); const { express } = require('express'); const { makeExecutableSchema } = require('@graphql-tools/schema'); const { WebSocketServer } = require('ws'); const { useServer } = require('graphql-ws/lib/use/ws'); const { PubSub } = require('graphql-subscriptions'); const cors = require('cors'); const bodyParser = require('body-parser'); const app = require('express')(); // 1. Create PubSub instance (Publish/Subscribe) const pubsub = new PubSub(); // 2. Define Schema const typeDefs = ` type Message { id: ID! user: String! content: String! } type Query { messages: [Message!] } type Mutation { postMessage(user: String!, content: String!): ID! } type Subscription { messages: [Message!] } `; const messages = []; // In-memory database // 3. Define Resolvers const resolvers = { Query: { messages: () => messages, }, Mutation: { postMessage: (parent, { user, content }) => { const id = messages.length + 1; const newMessage = { id, user, content }; messages.push(newMessage); // Publish the event to the 'POST_CREATED' channel // We send the *whole updated list* for simplicity in this demo pubsub.publish('POST_CREATED', { messages: messages }); return id; }, }, Subscription: { messages: { // Listen to the 'POST_CREATED' channel subscribe: () => pubsub.asyncIterator(['POST_CREATED']), }, }, }; // 4. Create Schema and HTTP Server setup const schema = makeExecutableSchema({ typeDefs, resolvers }); const httpServer = createServer(app); // 5. Set up WebSocket Server const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql', }); const serverCleanup = useServer({ schema }, wsServer); // 6. Set up Apollo Server const server = new ApolloServer({ schema, plugins: [ // Proper shutdown for the WebSocket server { async serverWillStart() { return { async drainServer() { await serverCleanup.dispose(); }, }; }, }, ], }); await server.start(); app.use('/graphql', cors(), bodyParser.json(), expressMiddleware(server)); const PORT = 4000; httpServer.listen(PORT, () => { console.log(`🚀 Server ready at http://localhost:${PORT}/graphql`); console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}/graphql`); }); -
Run the server:
node index.js
Part 2: The React Frontend (Apollo Client)
Now, let's create the React app that connects to the WebSocket.
-
Create the React app (in the root
graphql-subs-demofolder, not insideserver):# Open a NEW terminal window cd .. npx create-react-app client cd client -
Install Apollo Client dependencies:
npm install @apollo/client graphql graphql-ws -
Configure Apollo Client (
src/index.js): We need a Split Link. This directs HTTP requests (Queries/Mutations) tohttp://and Subscription requests tows://.// src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { ApolloClient, InMemoryCache, ApolloProvider, split, HttpLink } from '@apollo/client'; import { getMainDefinition } from '@apollo/client/utilities'; import { GraphQLWsLink } from '@apollo/client/link/subscriptions'; import { createClient } from 'graphql-ws'; // 1. HTTP Link for Queries and Mutations const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql', }); // 2. WebSocket Link for Subscriptions const wsLink = new GraphQLWsLink(createClient({ url: 'ws://localhost:4000/graphql', })); // 3. The Split function // If the operation is a subscription, use wsLink, otherwise use httpLink const splitLink = split( ({ query }) => { const definition = getMainDefinition(query); return ( definition.kind === 'OperationDefinition' && definition.operation === 'subscription' ); }, wsLink, httpLink, ); // 4. Initialize Client const client = new ApolloClient({ link: splitLink, cache: new InMemoryCache(), }); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <ApolloProvider client={client}> <App /> </ApolloProvider> ); -
Implement the Chat Component (
src/App.js): We will create a component that listens for new messages and a form to send them.// src/App.js import React, { useState } from 'react'; import { gql, useSubscription, useMutation } from '@apollo/client'; import './App.css'; // Optional basic styling // A. Define GraphQL strings const GET_MESSAGES = gql` subscription OnMessageAdded { messages { id user content } } `; const POST_MESSAGE = gql` mutation PostMessage($user: String!, $content: String!) { postMessage(user: $user, content: $content) } `; function Messages() { // B. Subscriptions Hook // This will automatically update whenever the server publishes data const { data, loading } = useSubscription(GET_MESSAGES); if (loading) return <p>Waiting for messages...</p>; if (!data) return null; return ( <div style={{ marginBottom: '20px' }}> {data.messages.map(({ id, user, content }) => ( <div key={id} style={{ border: '1px solid #ccc', padding: '10px', margin: '5px' }}> <strong>{user}:</strong> {content} </div> ))} </div> ); } function App() { const [user, setUser] = useState("Anonymous"); const [content, setContent] = useState(""); // C. Mutation Hook const [postMessage] = useMutation(POST_MESSAGE); const handleSubmit = (e) => { e.preventDefault(); if(!content) return; postMessage({ variables: { user, content } }); setContent(""); // Clear input }; return ( <div style={{ padding: "20px", maxWidth: "500px", margin: "0 auto" }}> <h1>Live Chat 🚀</h1> {/* The Subscription Component */} <Messages /> {/* The Input Area */} <form onSubmit={handleSubmit} style={{ display: 'flex', gap: '10px' }}> <input type="text" placeholder="User" value={user} onChange={(e) => setUser(e.target.value)} style={{ width: '100px' }} /> <input type="text" placeholder="Message..." value={content} onChange={(e) => setContent(e.target.value)} style={{ flex: 1 }} /> <button type="submit">Send</button> </form> </div> ); } export default App; -
Run the Client:
npm start
How to test it
- Ensure your Server is running on
localhost:4000. - Ensure your React Client is running (usually
localhost:3000). - Open two separate browser tabs pointing to
http://localhost:3000. - Type a message in Tab 1 and check Tab 2.
- Result: The message will appear instantly in Tab 2 without refreshing the page.
Key Concepts
PubSub(Backend): This is a simple event emitter. When a mutation happens, wepublishto a specific topic string ('POST_CREATED').subscriptionResolver (Backend): This listens to that topic usingpubsub.asyncIterator.splitLink (Frontend): This is the router of Apollo Client. It looks at the GraphQL query. If the keyword issubscription, it sends it down the WebSocket pipe. If it'squeryormutation, it sends it down the standard HTTP pipe.useSubscription(Frontend): This hook keeps a persistent connection open. UnlikeuseQuerywhich runs once,useSubscriptionstays active and triggers a re-render every time the server pushes new data.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.