Best examples of using fragments in GraphQL API (with real patterns)
Quick, concrete examples of using fragments in GraphQL API queries
Let’s start with the part everyone actually cares about: what does a useful fragment look like in a real query?
Here’s a straightforward example of using fragments in GraphQL API requests for a user profile that appears in multiple parts of an app:
fragment UserProfileFields on User {
id
username
avatarUrl
bio
}
query GetCurrentUser {
me {
...UserProfileFields
email
}
}
query GetPostAuthors {
posts(limit: 10) {
id
title
author {
...UserProfileFields
}
}
}
This is one of the best examples of using fragments in GraphQL API design: the UserProfileFields fragment defines the shared shape of a user wherever it appears. You change it in exactly one place, and every query using it stays in sync.
Real examples of using fragments in GraphQL API design
Let’s walk through several real examples of using fragments in GraphQL API schemas and clients. These are drawn from patterns you’ll see in production systems at SaaS companies, e‑commerce platforms, and content apps.
Shared product card fields across web and mobile
Imagine you have a product catalog that powers both a React web app and a React Native mobile app. Both platforms show a “product card” with the same core fields.
A clean example of using fragments in GraphQL API queries looks like this:
fragment ProductCardFields on Product {
id
name
thumbnailUrl
price {
amount
currency
}
rating
}
query HomePageProducts {
featuredProducts {
...ProductCardFields
}
}
query SearchProducts($query: String!) {
searchProducts(query: $query) {
...ProductCardFields
}
}
Your web and mobile components can both import and use ProductCardFields. In 2024, this pattern is common in mono-repos where both apps share a fragments.graphql file and a generated TypeScript type for ProductCardFields via tools like GraphQL Code Generator.
Polymorphic feeds with inline fragments
Feeds are everywhere: activity streams, notifications, social timelines. They often contain mixed content types (posts, comments, likes, follows). This is where inline fragments shine.
Here’s an example of using fragments in GraphQL API feeds with a union type:
union FeedItem = Post | Comment | Follow
query GetFeed($limit: Int!) {
feed(limit: $limit) {
id
createdAt
actor {
id
username
}
item {
__typename
... on Post {
id
title
body
}
... on Comment {
id
body
postId
}
... on Follow {
id
targetUser {
id
username
}
}
}
}
}
This is one of the best examples of using fragments in GraphQL API design for polymorphism. Each inline fragment (... on Post, ... on Comment) only requests fields valid for that type, keeping the query type-safe and self-documenting.
Reusing fragments for pagination (cursor-based)
Cursor-based pagination is the preferred pattern in 2024 for GraphQL APIs. You often repeat the same edges and node selections across many lists. A practical example of using fragments in GraphQL API pagination is:
fragment UserListItem on User {
id
username
avatarUrl
}
query GetFollowers(\(userId: ID!, \)after: String) {
user(id: $userId) {
id
followers(first: 20, after: $after) {
edges {
cursor
node {
...UserListItem
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
query GetFollowing(\(userId: ID!, \)after: String) {
user(id: $userId) {
id
following(first: 20, after: $after) {
edges {
cursor
node {
...UserListItem
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
Now your UI has a stable UserListItem shape for any list of users, and your tests only need to assert that fragment once.
Co-locating fragments with UI components (React / Relay / Apollo)
Modern GraphQL clients strongly encourage co-locating fragments with components. A component declares the exact data it needs via a fragment, and parent queries compose those fragments.
Here’s a React example of using fragments in GraphQL API-driven UIs with Apollo:
## userProfileFragment.graphql
fragment UserProfileFragment on User {
id
username
avatarUrl
bio
}
// UserProfile.tsx
import { gql, useFragment } from '@apollo/client';
import userProfileFragment from './userProfileFragment.graphql';
export function UserProfile(props) {
const data = useFragment(userProfileFragment, props.user);
return (
<div>
<img src={data.avatarUrl} alt={data.username} />
<h2>{data.username}</h2>
<p>{data.bio}</p>
</div>
);
}
Then a parent query simply spreads the fragment:
query GetUserProfilePage($id: ID!) {
user(id: $id) {
...UserProfileFragment
email
}
}
This pattern is one of the best examples of using fragments in GraphQL API integrations with component-based frameworks: your UI and data requirements live side by side.
Type-safe code generation with fragments (2024 trend)
A big 2024–2025 trend is leaning on fragments as the unit of type generation. Tools like GraphQL Code Generator or Relay Compiler output strongly typed models for each fragment, and your code consumes those models directly.
A concrete example of using fragments in GraphQL API type generation with TypeScript:
fragment OrderSummary on Order {
id
total {
amount
currency
}
status
}
query GetOrders {
orders(limit: 10) {
...OrderSummary
}
}
Your codegen config might look like:
generates:
src/generated/graphql.ts:
schema: schema.graphql
documents: 'src/**/*.graphql'
plugins:
- typescript
- typescript-operations
After running codegen, you get a OrderSummaryFragment TypeScript type. Your UI code can then accept OrderSummaryFragment as props, with full static checking.
This pattern appears in many real examples of using fragments in GraphQL API codebases at scale, because it isolates data shapes and makes refactors far less risky.
Fragments for security and field whitelisting
Fragments also help with security by standardizing which fields are exposed to certain roles. Consider an internal admin panel versus a public client.
You might define:
fragment PublicUserFields on User {
id
username
avatarUrl
}
fragment AdminUserFields on User {
id
username
avatarUrl
email
lastLoginIp
roles
}
``
Public queries only spread `PublicUserFields`, while admin queries spread `AdminUserFields`. In audits or code reviews, this gives you concrete examples of using fragments in GraphQL API access control: you can quickly see which data shapes are allowed for which clients.
For broader security best practices around APIs and data exposure, resources like the [NIST Secure Software Development Framework](https://csrc.nist.gov/publications) offer useful context, even though they’re not GraphQL-specific.
### Error handling and fragments on shared error types
If your GraphQL API returns typed errors (for example, via unions like `LoginResult = LoginSuccess | LoginError`), fragments keep your error handling consistent.
Example of using fragments in GraphQL API error responses:
```graphql
type LoginError {
code
message
field
}
type LoginSuccess {
user: User
token: String
}
union LoginResult = LoginSuccess | LoginError
fragment LoginErrorFields on LoginError {
code
message
field
}
query Login($input: LoginInput!) {
login(input: $input) {
__typename
... on LoginSuccess {
user {
id
username
}
token
}
... on LoginError {
...LoginErrorFields
}
}
}
Any client that needs to display form errors can reuse LoginErrorFields. This is one of the more underrated examples of using fragments in GraphQL API design: consistent, typed error contracts.
Patterns and anti-patterns: using fragments without shooting yourself in the foot
Fragments are powerful, but you can absolutely overdo it. Here are patterns that show up in the best examples of using fragments in GraphQL API implementations, and a few that tend to cause trouble.
Good patterns
Use fragments to:
- Represent reusable UI building blocks, like user chips, product cards, or order summaries.
- Define canonical shapes for domain entities (for example,
UserProfile,OrderSummary,ProductDetail). - Drive code generation so each fragment has a corresponding, strongly typed model in your client.
- Isolate role-based views of data (public vs admin, mobile vs internal tools).
In other words, the best examples of using fragments in GraphQL API design treat fragments as contracts between server and client, not just a convenience macro.
Painful anti-patterns
Watch out for:
- One giant fragment on a type that every query spreads. That’s just a glorified
SELECT *and defeats GraphQL’s selective querying. - Deeply nested fragments of fragments that make it impossible to understand what a query actually fetches without tooling.
- Duplicated fragments with slightly different names (
UserFields,UserFields2,UserFieldsForProfile) that drift apart.
When you see these, refactor toward fewer, clearer fragments that match real UI or domain concepts.
How fragments interact with caching and performance in 2024–2025
Modern GraphQL clients like Apollo Client and Relay use fragments as a hint for caching and normalization.
- Apollo normalizes data by
idand__typename, and fragments define which fields are read and written consistently. - Relay’s entire model is fragment-centric; data dependencies are expressed almost entirely as fragments.
In practice, real examples of using fragments in GraphQL API clients for performance include:
- A list page and a detail page sharing a
ProductCardFieldsfragment so the detail page can render instantly from the cache when navigated to from the list. - A notifications dropdown and a full notifications page sharing a
NotificationItemfragment, making sure cache hits are consistent and predictable.
When you keep fragments stable and well-named, your cache becomes more reliable, and you avoid subtle bugs where one query forgets to request a field another part of the UI expects.
For general guidance on performance and network efficiency (even beyond GraphQL), the U.S. General Services Administration’s web performance guidance is a solid reference, especially if you’re working on public-facing services.
FAQ: common questions and examples of using fragments in GraphQL API
What is a simple example of using fragments in GraphQL API queries?
A very simple example is a fragment for a reusable user snippet:
fragment SimpleUser on User {
id
username
}
query GetMe {
me {
...SimpleUser
}
}
query GetPostAuthor($id: ID!) {
post(id: $id) {
id
author {
...SimpleUser
}
}
}
Both queries share the same SimpleUser shape with no duplication.
When should I avoid fragments?
Skip fragments when a field selection is used exactly once and is unlikely to be reused. For tiny, one-off queries, fragments add ceremony without real benefit. Also avoid creating a single, massive fragment that every query spreads; that pattern erases the main advantage of GraphQL: asking only for what you need.
Are fragments bad for performance?
No. On the wire, fragments are just syntactic sugar. The server receives a fully expanded query. Performance issues usually come from requesting too many fields, not from using fragments themselves. In fact, many of the best examples of using fragments in GraphQL API clients improve performance by making it easier to reuse cached data.
How many fragments are too many?
There’s no hard number. A practical rule: if another engineer can read a query and understand the data shape without constantly jumping between files, you’re fine. If every query turns into a scavenger hunt across ten fragments, you probably need to consolidate.
Can fragments help with API evolution over time?
Yes. In long-lived systems, fragments act as stable contracts. You can add fields to types without breaking existing fragments. You can also introduce new fragments (for example, UserPrivacySafeFields) and gradually migrate clients. Many real examples of using fragments in GraphQL API migrations use this pattern to roll out schema changes safely.
For broader thinking on API evolution and long-term maintenance, academic and industry research on software evolution from universities like Carnegie Mellon is worth a look.
Putting it into practice
If you remember nothing else, remember this: the strongest examples of using fragments in GraphQL API design are the ones that mirror how your UI and domain are structured.
- Define fragments around meaningful concepts: profile, card, list item, summary.
- Share those fragments across web, mobile, and internal tools.
- Let your code generator turn them into typed models.
- Use inline fragments for polymorphic content and typed errors.
Start by extracting one or two obvious fragments from your largest queries — maybe a UserProfile or ProductCard — and wire them into your client. Once you see how much cleaner your queries and types become, you’ll know where to apply fragments next.
Related Topics
Best examples of using fragments in GraphQL API (with real patterns)
Practical examples of using directives in GraphQL (with real patterns)
Real-world examples of GraphQL with Node.js: 3 practical builds you can copy
Real-world examples of optimizing GraphQL queries
Real-world examples of GraphQL with TypeScript: practical examples for 2025
Examples of Schema Definition in GraphQL: 3 Practical Examples for Real APIs
Explore More GraphQL API Examples
Discover more examples and insights in this category.
View All GraphQL API Examples