This is a comprehensive request to build a Next.js app with GraphQL, Apollo Client, GraphQL Code Generator, and implement optimistic UI updates with rollback on error. Let me break this down:
- Next.js Setup - Framework and routing
- GraphQL - Backend schema and server setup
- GraphQL Code Generator - Generate typed hooks from schema
- TypedDocumentNode - Type-safe document nodes
- Apollo Client - State management and caching
- Optimistic Updates - Immediately update UI before server response
- Error Handling & Rollback - Restore previous state on error
I'll create a complete, production-ready example with:
- Next.js app structure
- GraphQL schema
- Apollo Server setup
- GraphQL Code Generator configuration
- Custom hooks with optimistic updates
- Proper error handling and rollback
- Beautiful UI components
- Testing examples
Let me structure this comprehensively:
Next.js + GraphQL + Optimistic UI Updates
I'll build a complete app with typed GraphQL hooks and optimistic updates with rollback.
1. Project Setup
npm create next-app@latest graphql-app -- --typescript --tailwind
cd graphql-app
npm install @apollo/client graphql subscriptions-transport-ws
npm install graphql-codegen @graphql-codegen/client-preset @graphql-codegen/typescript
npm install -D @graphql-codegen/cli typescript-plugin-codegen
npm install apollo-server-standalone
npm install concurrently dotenv
2. GraphQL Schema
# schema.graphql
scalar DateTime
type Query {
posts(limit: Int = 10): [Post!]!
post(id: ID!): Post
me: User
}
type Mutation {
toggleLike(postId: ID!): Post!
createPost(title: String!, content: String!): Post!
deletePost(id: ID!): Boolean!
}
type User {
id: ID!
name: String!
email: String!
likes: [ID!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
likes: Int!
liked: Boolean!
createdAt: DateTime!
updatedAt: DateTime!
}
type Subscription {
postLiked(postId: ID!): Post!
}
3. Apollo Server Setup
// server/apollo-server.ts
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "apollo-server-standalone";
import { readFileSync } from "fs";
import { resolve } from "path";
// Mock database
const posts = [
{
id: "1",
title: "First Post",
content: "Hello World",
authorId: "user-1",
likes: 5,
createdAt: new Date("2024-01-01"),
updatedAt: new Date("2024-01-01"),
},
{
id: "2",
title: "Second Post",
content: "GraphQL is awesome",
authorId: "user-1",
likes: 12,
createdAt: new Date("2024-01-02"),
updatedAt: new Date("2024-01-02"),
},
];
const userLikes: { [userId: string]: string[] } = {
"user-1": ["1"],
};
const users = [
{
id: "user-1",
name: "John Doe",
email: "john@example.com",
},
];
const typeDefs = readFileSync(resolve("./schema.graphql"), "utf-8");
const resolvers = {
Query: {
posts: (_: any, { limit }: { limit: number }) => posts.slice(0, limit),
post: (_: any, { id }: { id: string }) =>
posts.find((p) => p.id === id),
me: () => users[0],
},
Mutation: {
toggleLike: async (
_: any,
{ postId }: { postId: string },
{ userId }: any
) => {
// Simulate network delay
await new Promise((resolve) => setTimeout(resolve, 800));
const post = posts.find((p) => p.id === postId);
if (!post) throw new Error("Post not found");
const userLikeArray = userLikes[userId] || [];
const likeIndex = userLikeArray.indexOf(postId);
if (likeIndex > -1) {
userLikeArray.splice(likeIndex, 1);
post.likes--;
} else {
userLikeArray.push(postId);
post.likes++;
}
userLikes[userId] = userLikeArray;
post.updatedAt = new Date();
return post;
},
createPost: (
_: any,
{ title, content }: { title: string; content: string },
{ userId }: any
) => {
const newPost = {
id: String(posts.length + 1),
title,
content,
authorId: userId,
likes: 0,
createdAt: new Date(),
updatedAt: new Date(),
};
posts.push(newPost);
return newPost;
},
deletePost: (_: any, { id }: { id: string }) => {
const index = posts.findIndex((p) => p.id === id);
if (index > -1) {
posts.splice(index, 1);
return true;
}
return false;
},
},
Post: {
author: (post: any) => users.find((u) => u.id === post.authorId),
liked: (post: any, _: any, { userId }: any) => {
return (userLikes[userId] || []).includes(post.id);
},
},
User: {
likes: (user: any) => userLikes[user.id] || [],
},
};
async function startServer() {
const server = new ApolloServer({
typeDefs,
resolvers,
});
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
context: async () => ({
userId: "user-1", // In production, extract from auth token
}),
});
console.log(`🚀 Server ready at ${url}`);
}
startServer().catch(console.error);
4. GraphQL Code Generator Config
// codegen.ts
import type { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
schema: "./schema.graphql",
documents: "./src/**/*.ts{,x}",
generates: {
"./src/graphql/generated/": {
preset: "client",
plugins: [],
presetConfig: {
fragmentMasking: false,
},
config: {
useTypeImports: true,
documentMode: "documentOnly",
exposeQueryKeys: true,
exposeSetupHelpers: true,
},
},
},
};
export default config;
5. Generated Types & Hooks
// src/graphql/generated/graphql.ts
/* eslint-disable */
import type { TypedDocumentNode as DocumentNode } from "@apollo/client";
import type {
DocumentNode as RawDocumentNode,
OperationVariables,
} from "graphql";
export type Maybe<T> = T | null;
export type InputMaybe<T> = Maybe<T>;
export type Exact<T extends { [key: string]: unknown }> = {
[K in keyof T]: T[K];
};
export type Post = {
__typename?: "Post";
id: string;
title: string;
content: string;
author: User;
likes: number;
liked: boolean;
createdAt: any;
updatedAt: any;
};
export type User = {
__typename?: "User";
id: string;
name: string;
email: string;
likes: Array<string>;
};
export type Query = {
__typename?: "Query";
posts: Array<Post>;
post?: Maybe<Post>;
me?: Maybe<User>;
};
export type QueryPostsArgs = {
limit?: InputMaybe<number>;
};
export type QueryPostArgs = {
id: string;
};
export type Mutation = {
__typename?: "Mutation";
toggleLike: Post;
createPost: Post;
deletePost: boolean;
};
export type MutationToggleLikeArgs = {
postId: string;
};
export type MutationCreatePostArgs = {
title: string;
content: string;
};
export type MutationDeletePostArgs = {
id: string;
};
export type GetPostsQueryVariables = Exact<{
limit?: InputMaybe<number>;
}>;
export type GetPostsQuery = {
__typename?: "Query";
posts: Array<{
__typename?: "Post";
id: string;
title: string;
content: string;
likes: number;
liked: boolean;
author: { __typename?: "User"; id: string; name: string };
}>;
};
export type ToggleLikeMutationVariables = Exact<{
postId: string;
}>;
export type ToggleLikeMutation = {
__typename?: "Mutation";
toggleLike: {
__typename?: "Post";
id: string;
likes: number;
liked: boolean;
};
};
export const GetPostsDocument = {
kind: "Document",
definitions: [
{
kind: "OperationDefinitionNode",
operation: "query",
name: { kind: "NameNode", value: "GetPosts" },
// ... more definitions
},
],
} as unknown as DocumentNode<GetPostsQuery, GetPostsQueryVariables>;
export const ToggleLikeDocument = {
kind: "Document",
definitions: [
{
kind: "OperationDefinitionNode",
operation: "mutation",
name: { kind: "NameNode", value: "ToggleLike" },
// ... more definitions
},
],
} as unknown as DocumentNode<ToggleLikeMutation, ToggleLikeMutationVariables>;
6. GraphQL Documents
# src/graphql/queries/getPosts.graphql
query GetPosts($limit: Int) {
posts(limit: $limit) {
id
title
content
likes
liked
author {
id
name
}
}
}
# src/graphql/mutations/toggleLike.graphql
mutation ToggleLike($postId: ID!) {
toggleLike(postId: $postId) {
id
likes
liked
}
}
7. Apollo Client Setup
// src/lib/apollo-client.ts
import {
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
Observable,
gql,
} from "@apollo/client";
import { onError } from "@apollo/client/link/error";
const httpLink = new HttpLink({
uri: "http://localhost:4000",
credentials: "omit",
});
const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) => {
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
});
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
export const client = new ApolloClient({
ssrMode: typeof window === "undefined",
link: ApolloLink.from([errorLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
merge(existing = [], incoming) {
return incoming;
},
},
},
},
Post: {
keyFields: ["id"],
},
},
}),
});
8. Custom Hook with Optimistic Updates & Rollback
// src/hooks/useToggleLike.ts
import { useMutation } from "@apollo/client";
import type {
ToggleLikeMutation,
ToggleLikeMutationVariables,
} from "@/graphql/generated/graphql";
import { ToggleLikeDocument, GetPostsDocument } from "@/graphql/generated/graphql";
import { UseApolloMutationHookOptions } from "@apollo/client";
interface UseToggleLikeOptions
extends UseApolloMutationHookOptions<
ToggleLikeMutation,
ToggleLikeMutationVariables
> {
onSuccess?: (data: ToggleLikeMutation) => void;
onError?: (error: Error) => void;
}
export function useToggleLike(options?: UseToggleLikeOptions) {
const [mutate, result] = useMutation(ToggleLikeDocument, {
update(cache, { data }) {
if (!data?.toggleLike) return;
const { id, likes, liked } = data.toggleLike;
// Update the specific post in cache
cache.modify({
fields: {
posts(existingPosts = []) {
return existingPosts.map((postRef: any) => {
if (postRef.__ref === `Post:${id}`) {
cache.modify({
id: cache.identify(postRef),
fields: {
likes: () => likes,
liked: () => liked,
},
});
}
return postRef;
});
},
},
});
},
onCompleted(data) {
options?.onSuccess?.(data);
},
onError(error) {
options?.onError?.(error);
},
...options,
});
const toggleLike = async (postId: string) => {
try {
await mutate({
variables: { postId },
optimisticResponse: {
__typename: "Mutation",
toggleLike: {
__typename: "Post",
id: postId,
likes: 0, // Will be calculated from cache
liked: true, // Will be toggled
__typename: "Post",
},
},
});
} catch (error) {
console.error("Failed to toggle like:", error);
throw error;
}
};
return {
toggleLike,
loading: result.loading,
error: result.error,
};
}
9. Advanced Hook with Cache Management
// src/hooks/useToggleLikeAdvanced.ts
import { useMutation, useReactiveVar, ApolloCache } from "@apollo/client";
import {
ToggleLikeMutation,
ToggleLikeMutationVariables,
GetPostsQuery,
} from "@/graphql/generated/graphql";
import { ToggleLikeDocument, GetPostsDocument } from "@/graphql/generated/graphql";
import { makeVar } from "@apollo/client";
// Track optimistic updates for rollback
export const optimisticUpdatesVar = makeVar<
Map<string, { before: number; after: number; liked: boolean }>
>(new Map());
export function useToggleLikeAdvanced() {
const updates = useReactiveVar(optimisticUpdatesVar);
const [mutate, result] = useMutation(ToggleLikeDocument);
const toggleLike = async (postId: string) => {
// Get current cache data
const normCache = result.apolloClient?.cache.readQuery({
query: GetPostsDocument,
});
if (!normCache) throw new Error("Cache not available");
const posts = normCache.posts;
const post = posts.find((p) => p.id === postId);
if (!post) throw new Error("Post not found");
// Store previous state for rollback
const previousData = {
before: post.likes,
after: post.liked ? post.likes - 1 : post.likes + 1,
liked: !post.liked,
};
const newUpdates = new Map(updates);
newUpdates.set(postId, previousData);
optimisticUpdatesVar(newUpdates);
try {
const { data } = await mutate({
variables: { postId },
optimisticResponse: {
__typename: "Mutation",
toggleLike: {
__typename: "Post",
id: postId,
likes: previousData.after,
liked: previousData.liked,
},
},
});
// Clear optimistic update on success
newUpdates.delete(postId);
optimisticUpdatesVar(newUpdates);
return data;
} catch (error) {
// Rollback on error
console.error("Like failed, rolling back");
result.apolloClient?.cache.modify({
fields: {
posts(existingPosts: any[]) {
return existingPosts.map((postRef: any) => {
if (postRef.__ref === `Post:${postId}`) {
result.apolloClient?.cache.modify({
id: result.apolloClient?.cache.identify(postRef),
fields: {
likes: () => previousData.before,
liked: () => !previousData.liked,
},
});
}
return postRef;
});
},
},
});
newUpdates.delete(postId);
optimisticUpdatesVar(newUpdates);
throw error;
}
};
return {
toggleLike,
loading: result.loading,
error: result.error,
optimisticUpdates: updates,
};
}
10. Post Card Component
// src/components/PostCard.tsx
"use client";
import { useState } from "react";
import Link from "next/link";
import type { GetPostsQuery } from "@/graphql/generated/graphql";
import { useToggleLikeAdvanced } from "@/hooks/useToggleLikeAdvanced";
type Post = GetPostsQuery["posts"][0];
interface PostCardProps {
post: Post;
}
export function PostCard({ post }: PostCardProps) {
const { toggleLike, loading, error, optimisticUpdates } =
useToggleLikeAdvanced();
const [showError, setShowError] = useState(false);
const isOptimistic = optimisticUpdates.has(post.id);
const update = optimisticUpdates.get(post.id);
// Show optimistic values while loading
const displayLikes = isOptimistic ? update?.after ?? post.likes : post.likes;
const displayLiked = isOptimistic ? update?.liked ?? post.liked : post.liked;
const handleToggleLike = async () => {
try {
setShowError(false);
await toggleLike(post.id);
} catch (err) {
setShowError(true);
setTimeout(() => setShowError(false), 3000);
}
};
return (
<article
className={`rounded-lg border border-gray-200 p-6 shadow-sm transition-all duration-200 ${
isOptimistic ? "opacity-75" : "opacity-100"
}`}
>
<div className="mb-4">
<h2 className="text-xl font-bold text-gray-900 mb-2">{post.title}</h2>
<p className="text-gray-600 text-sm">
By {post.author.name} • 2 days ago
</p>
</div>
<p className="text-gray-700 mb-4">{post.content}</p>
<div className="flex items-center justify-between">
<button
onClick={handleToggleLike}
disabled={loading}
className={`inline-flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all duration-200 ${
displayLiked
? "bg-red-100 text-red-600 hover:bg-red-200"
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
} disabled:opacity-50 disabled:cursor-not-allowed`}
>
<HeartIcon filled={displayLiked} />
<span>{displayLikes}</span>
{loading && <Spinner />}
</button>
{showError && (
<div className="text-sm text-red-600 flex items-center gap-1">
<XIcon />
Failed to update like
</div>
)}
</div>
{isOptimistic && (
<div className="mt-2 text-xs text-blue-600 flex items-center gap-1">
<Spinner size="sm" />
Updating...
</div>
)}
</article>
);
}
function HeartIcon({ filled }: { filled: boolean }) {
return filled ? (
<svg
className="w-5 h-5"
viewBox="0 0 24 24"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
) : (
<svg
className="w-5 h-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
);
}
function Spinner({ size = "md" }: { size?: "sm" | "md" }) {
return (
<svg
className={`animate-spin ${size === "sm" ? "w-3 h-3" : "w-4 h-4"}`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
);
}
function XIcon() {
return (
<svg
className="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
);
}
11. Posts Feed Page
// src/pages/index.tsx
"use client";
import { useQuery } from "@apollo/client";
import { GetPostsDocument } from "@/graphql/generated/graphql";
import { PostCard } from "@/components/PostCard";
import { ApolloProvider } from "@apollo/client";
import { client } from "@/lib/apollo-client";
function PostsFeedContent() {
const { data, loading, error } = useQuery(GetPostsDocument, {
variables: { limit: 20 },
});
if (loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
<p className="mt-4 text-gray-600">Loading posts...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="flex items-center justify-center min-h-screen bg-red-50">
<div className="text-center">
<h2 className="text-2xl font-bold text-red-600 mb-2">
Failed to Load Posts
</h2>
<p className="text-red-600 mb-4">{error.message}</p>
<button
onClick={() => window.location.reload()}
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
>
Try Again
</button>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 py-8">
<div className="max-w-2xl mx-auto px-4">
<header className="mb-8">
<h1 className="text-4xl font-bold text-gray-900 mb-2">
Social Feed
</h1>
<p className="text-gray-600">
{data?.posts.length} posts with optimistic updates
</p>
</header>
<div className="space-y-6">
{data?.posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
</div>
</div>
);
}
export default function PostsFeed() {
return (
<ApolloProvider client={client}>
<PostsFeedContent />
</ApolloProvider>
);
}
12. Next.js Layout
// src/app/layout.tsx
import "./globals.css";
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "GraphQL Social Feed",
description: "Next.js + GraphQL with optimistic UI updates",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className="font-sans">{children}</body>
</html>
);
}
13. Environment Variables
# .env.local
NEXT_PUBLIC_GRAPHQL_URL=http://localhost:4000
14. Package.json Scripts
{
"scripts": {
"dev": "concurrently \"npm run server:dev\" \"npm run client:dev\"",
"server:dev": "ts-node server/apollo-server.ts",
"client:dev": "next dev",
"build": "npm run codegen && next build",
"codegen": "graphql-codegen",
"codegen:watch": "graphql-codegen --watch",
"start": "next start",
"lint": "eslint src"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"typescript": "^5",
"tailwindcss": "^3",
"postcss": "^8",
"autoprefixer": "^10",
"ts-node": "^10",
"concurrently": "^8"
}
}
15. Advanced Cache Update Utility
// src/lib/cache-utils.ts
import { ApolloCache } from "@apollo/client";
import type { Post } from "@/graphql/generated/graphql";
export interface CacheUpdate {
postId: string;
previousState: Partial<Post>;
newState: Partial<Post>;
timestamp: number;
}
export class CacheManager {
private updates: Map<string, CacheUpdate> = new Map();
recordUpdate(
postId: string,
previousState: Partial<Post>,
newState: Partial<Post>
) {
this.updates.set(postId, {
postId,
previousState,
newState,
timestamp: Date.now(),
});
}
getUpdate(postId: string) {
return this.updates.get(postId);
}
clearUpdate(postId: string) {
this.updates.delete(postId);
}
rollback(cache: ApolloCache<any>, postId: string) {
const update = this.updates.get(postId);
if (!update) return;
cache.modify({
id: cache.identify({ __typename: "Post", id: postId }),
fields: {
likes: () => update.previousState.likes,
liked: () => update.previousState.liked,
},
});
this.clearUpdate(postId);
}
clearStale(maxAge: number = 5 * 60 * 1000) {
const now = Date.now();
for (const [postId, update] of this.updates) {
if (now - update.timestamp > maxAge) {
this.updates.delete(postId);
}
}
}
}
export const cacheManager = new CacheManager();
16. Testing
// src/hooks/__tests__/useToggleLike.test.ts
import { renderHook, act, waitFor } from "@testing-library/react";
import { MockedProvider } from "@apollo/client/testing";
import { useToggleLikeAdvanced } from "../useToggleLikeAdvanced";
import { ToggleLikeDocument } from "@/graphql/generated/graphql";
const mocks = [
{
request: {
query: ToggleLikeDocument,
variables: { postId: "1" },
},
result: {
data: {
toggleLike: {
__typename: "Post",
id: "1",
likes: 6,
liked: true,
},
},
},
},
];
describe("useToggleLike", () => {
it("should immediately update the UI (optimistic)", async () => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
const { result } = renderHook(() => useToggleLikeAdvanced(), {
wrapper,
});
await act(async () => {
const promise = result.current.toggleLike("1");
expect(result.current.optimisticUpdates.has("1")).toBe(true);
await promise;
});
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
it("should rollback on error", async () => {
const errorMocks = [
{
request: {
query: ToggleLikeDocument,
variables: { postId: "1" },
},
error: new Error("Network error"),
},
];
const wrapper = ({ children }: { children: React.ReactNode }) => (
<MockedProvider mocks={errorMocks}>{children}</MockedProvider>
);
const { result } = renderHook(() => useToggleLikeAdvanced(), {
wrapper,
});
await act(async () => {
try {
await result.current.toggleLike("1");
} catch (error) {
// Expected
}
});
expect(result.current.optimisticUpdates.has("1")).toBe(false);
});
});
17. Tailwind CSS Config
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx}",
"./src/components/**/*.{js,ts,jsx,tsx}",
"./src/app/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};
Running the App
# Terminal 1: Start the GraphQL server
npm run server:dev
# Terminal 2: Start the Next.js app
npm run client:dev
# Or both together:
npm run dev
# Generate types
npm run codegen:watch
Key Features
✅ Type-safe GraphQL hooks with TypedDocumentNode
✅ Optimistic UI updates - instant visual feedback
✅ Automatic rollback on errors with previous state restoration
✅ Cache management with Apollo Client
✅ GraphQL Code Generator for generated types
✅ Proper loading states and error handling
✅ React hooks for clean component logic
✅ Production-ready with tests and utilities
This setup provides a robust foundation for building real-time, responsive GraphQL applications with excellent user experience through optimistic updates!