Providing Next.js Apollo example with typed hooks and optimistic UI
Here's a minimal Next.js example using Apollo Client and GraphQL Code Generator configured with typedDocumentNode: true to generate typed hooks. The Like mutation uses an optimistic response that toggles isLiked and adjusts likesCount instantly, rolling back on error automatically. The setup includes Apollo client, codegen config, typed queries/mutations, and Next.js pages showing usage of generated hooks with types and optimistic updates.
Below is a minimal example showing how to wire up:
- Apollo Client in Next.js
- GraphQL Code Generator with
typedDocumentNode turned on
- A Like mutation with optimistic UI (toggle immediately, rollback on error)
It’s intentionally small so you can plug it into your own backend. Assumes a GraphQL API endpoint at http://localhost:4000/graphql with a toggleLike(postId: ID!): Post mutation returning { id, isLiked, likesCount }.
1) Install dependencies
npm install next react react-dom \
@apollo/client graphql \
@graphql-codegen/cli @graphql-codegen/typescript \
@graphql-codegen/typescript-operations @graphql-codegen/typescript-graphql-request \
@graphql-codegen/typed-document-node \
graphql-tag
Note: @graphql-codegen/typescript-graphql-request can be swapped out if you prefer the Apollo plugin; we’ll rely on typedDocumentNode so it works with @apollo/client.
2) GraphQL Codegen config (codegen.yml)
schema: "http://localhost:4000/graphql"
documents: "./graphql/**/*.graphql"
generates:
./graphql/generated.ts:
plugins:
- "typescript"
- "typescript-operations"
- "typed-document-node"
config:
# Ensures documents are generated as TypedDocumentNode
documentMode: "documentNode"
# Makes sure __typename is added for caching
addTypename: true
Run npx graphql-codegen --config codegen.yml after writing your .graphql files to generate graphql/generated.ts.
3) GraphQL operations (/graphql/queries.graphql and /graphql/mutations.graphql)
# /graphql/queries.graphql
query GetPosts {
posts {
id
title
isLiked
likesCount
}
}
# /graphql/mutations.graphql
mutation ToggleLike($postId: ID!) {
toggleLike(postId: $postId) {
id
isLiked
likesCount
}
}
4) Apollo client setup (/lib/apollo.ts)
// /lib/apollo.ts
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
export const apolloClient = new ApolloClient({
link: new HttpLink({
uri: "http://localhost:4000/graphql",
}),
cache: new InMemoryCache(),
});
5) _app.tsx to wrap with ApolloProvider
// /pages/_app.tsx
import { ApolloProvider } from "@apollo/client";
import type { AppProps } from "next/app";
import { apolloClient } from "../lib/apollo";
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
</ApolloProvider>
);
}
6) Example page showing posts with like toggling (/pages/index.tsx)
import React from "react";
import { useQuery, useMutation } from "@apollo/client";
import {
GetPostsDocument,
ToggleLikeDocument,
GetPostsQuery,
ToggleLikeMutation,
ToggleLikeMutationVariables,
} from "../graphql/generated";
export default function Home() {
const { data, loading, error } = useQuery<GetPostsQuery>(GetPostsDocument);
const [toggleLike] = useMutation<
ToggleLikeMutation,
ToggleLikeMutationVariables
>(ToggleLikeDocument);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error loading posts</p>;
const posts = data?.posts ?? [];
return (
<div style={{ padding: 20 }}>
<h1>Posts</h1>
{posts.map((post) => (
<div
key={post.id}
style={{
border: "1px solid #eee",
padding: 10,
marginBottom: 8,
borderRadius: 4,
}}
>
<h3>{post.title}</h3>
<p>Likes: {post.likesCount}</p>
<button
onClick={() => {
toggleLike({
variables: { postId: post.id },
// Immediately toggle UI
optimisticResponse: {
__typename: "Mutation",
toggleLike: {
__typename: "Post",
id: post.id,
isLiked: !post.isLiked,
likesCount: post.likesCount + (post.isLiked ? -1 : 1),
},
},
// Update the cache
update: (cache, { data }) => {
if (!data?.toggleLike) return;
const postId = cache.identify({
__typename: "Post",
id: post.id,
});
cache.modify({
id: postId,
fields: {
isLiked: () => data.toggleLike.isLiked,
likesCount: () => data.toggleLike.likesCount,
},
});
},
// Rollback on error is automatic; Apollo will revert the optimistic changes
onError: () => {
// Optionally handle errors (toast, etc.)
},
});
}}
>
{post.isLiked ? "Unlike" : "Like"}
</button>
</div>
))}
</div>
);
}
How it works:
optimisticResponse immediately updates isLiked and likesCount in the UI before the server responds.
- The
update function ensures the final server result is written into the cache (or if the server response differs).
- If the mutation fails, Apollo automatically rolls back the optimistic update.
7) Generated types / hooks
After running npx graphql-codegen, you’ll see graphql/generated.ts containing:
GetPostsDocument, ToggleLikeDocument as TypedDocumentNode
- Typed operations like
GetPostsQuery, ToggleLikeMutation, etc.
You import them (as above) into your components to keep everything fully typed.
8) Running
- Make sure your GraphQL server is running at
http://localhost:4000/graphql with the GetPosts and toggleLike operations.
- Run
npm run dev (or yarn dev) in the Next.js project.
- Run
npx graphql-codegen whenever you change .graphql files to refresh the typed hooks and document nodes.
This setup gives you a typed, Apollo-based Next.js app with instant optimistic toggling for a Like feature, plus automatic rollback on any mutation error.