# Quick Start Instructions
## 1. Backend (GraphQL Server with Subscriptions)
Create a new directory for the server:
```bash
mkdir graphql-chat-server
cd graphql-chat-server
npm init -y
npm install apollo-server graphql
Create server.js:
const { ApolloServer, PubSub, gql } = require('apollo-server');
const pubsub = new PubSub();
const typeDefs = gql`
type Message {
id: ID!
content: String!
author: String!
}
type Query {
messages: [Message!]!
}
type Mutation {
addMessage(content: String!, author: String!): Message!
}
type Subscription {
messageAdded: Message!
}
`;
let messages = [];
const resolvers = {
Query: {
messages: () => messages,
},
Mutation: {
addMessage: (_, { content, author }) => {
const id = String(messages.length + 1);
const message = { id, content, author };
messages.push(message);
pubsub.publish('MESSAGE_ADDED', { messageAdded: message });
return message;
},
},
Subscription: {
messageAdded: {
subscribe: () => pubsub.asyncIterator(['MESSAGE_ADDED']),
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`📡 Subscriptions ready at ${subscriptionsUrl}`);
});
Run the server:
node server.js
- HTTP endpoint:
http://localhost:4000/graphql
- WS endpoint:
ws://localhost:4000/graphql
2. Frontend (React App with Apollo Client)
In a new terminal:
npx create-react-app graphql-chat-client
cd graphql-chat-client
npm install @apollo/client graphql subscriptions-transport-ws
Replace src/App.js:
import React, { useState, useEffect } from 'react';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
useMutation,
useSubscription,
gql,
split,
HttpLink,
} from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
// GraphQL operations
const GET_MESSAGES = gql`
query GetMessages {
messages {
id
content
author
}
}
`;
const ADD_MESSAGE = gql`
mutation AddMessage($content: String!, $author: String!) {
addMessage(content: $content, author: $author) {
id
content
author
}
}
`;
const MESSAGE_ADDED = gql`
subscription {
messageAdded {
id
content
author
}
}
`;
// Apollo Client setup
const httpLink = new HttpLink({
uri: 'http://localhost:4000/graphql',
});
const wsLink = new WebSocketLink({
uri: 'ws://localhost:4000/graphql',
options: {
reconnect: true,
},
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
function Chat() {
const [messages, setMessages] = useState([]);
const [author, setAuthor] = useState('');
const [content, setContent] = useState('');
// Initial load
const { data: queryData, loading: queryLoading } = useQuery(GET_MESSAGES);
useEffect(() => {
if (queryData?.messages) {
setMessages(queryData.messages);
}
}, [queryData?.messages]);
// Live updates via subscription
const { data: subData } = useSubscription(MESSAGE_ADDED);
useEffect(() => {
if (subData?.messageAdded) {
setMessages((prev) => [...prev, subData.messageAdded]);
}
}, [subData?.messageAdded]);
// Send message
const [addMessage, { loading: mutationLoading }] = useMutation(ADD_MESSAGE);
const onSend = () => {
if (content.trim() && author.trim()) {
addMessage({ variables: { content: content.trim(), author: author.trim() } });
setContent('');
}
};
if (queryLoading) return <p>Loading messages...</p>;
return (
<div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
<h1>🗨️ Live GraphQL Chat</h1>
<p>Open multiple tabs/windows to see live updates!</p>
<ul style={{ listStyle: 'none', padding: 0, border: '1px solid #ccc', height: '400px', overflowY: 'scroll' }}>
{messages.map((message) => (
<li
key={message.id}
style={{
padding: '10px',
borderBottom: '1px solid #eee',
background: '#f9f9f9',
marginBottom: '5px',
}}
>
<strong>{message.author}:</strong> {message.content}
</li>
))}
</ul>
<div style={{ marginTop: '20px' }}>
<input
value={author}
onChange={(e) => setAuthor(e.target.value)}
placeholder="Your name"
style={{ marginRight: '10px', padding: '8px', width: '150px' }}
/>
<input
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
onKeyPress={(e) => e.key === 'Enter' && onSend()}
style={{ marginRight: '10px', padding: '8px', width: '300px' }}
/>
<button
onClick={onSend}
disabled={mutationLoading || !content.trim() || !author.trim()}
style={{
padding: '8px 16px',
background: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: mutationLoading ? 'not-allowed' : 'pointer',
}}
>
{mutationLoading ? 'Sending...' : 'Send'}
</button>
</div>
</div>
);
}
function App() {
return (
<ApolloProvider client={client}>
<Chat />
</ApolloProvider>
);
}
export default App;
Clean up src/App.css (optional, or remove import) and src/index.js is fine.
Run the client:
npm start
- Opens at
http://localhost:3000
How it Works
- Query: Loads initial messages.
- Mutation: Sends new messages (server publishes via PubSub).
- Subscription: All connected clients receive live updates and append to the list in real-time.
- Open 2+ browser tabs to test live sync!
Notes
- Uses Apollo Server v3 (simple subscriptions setup; v4 requires more config).
- Works out-of-the-box. Restart server to clear messages.
- For production, add auth, persistence (e.g., DB), optimistic UI, etc.
- Errors? Ensure server runs first, no port conflicts.
Enjoy your live GraphQL React app! 🕵️♂️