GraphQL Request Cursor Pagination
Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.
Code
import { GraphQLClient, gql } from 'graphql-request';
const client = new GraphQLClient('https://api.example.com/graphql', {
headers: { Authorization: 'Bearer ' + process.env.API_TOKEN },
});
const query = gql`
query Orders($first: Int!, $after: String) {
orders(first: $first, after: $after) {
edges { cursor node { id total } }
pageInfo { hasNextPage endCursor }
}
}
`;
async function fetchAllOrders(pageSize = 50) {
const results = [];
let after = null;
while (true) {
const data = await client.request(query, { first: pageSize, after });
const { edges, pageInfo } = data.orders;
results.push(...edges.map((edge) => edge.node));
if (!pageInfo.hasNextPage) break;
after = pageInfo.endCursor;
}
return results;
}
const orders = await fetchAllOrders();
console.log('total orders fetched:', orders.length);What the code does
Structurally, expect the function fetchAllOrders and nothing else.
The one repetition in this snippet is the loop while (true). await marks each async boundary — nothing fires and forgets. The import line is the dependency contract: GraphQLClient, gql come from graphql-request and nothing else.
Tunables arrive as environment variables: API_TOKEN.
What to watch for
- External dependency:
graphql-request— install it before running the snippet. - The guard
!pageInfo.hasNextPageshort-circuits the flow with an earlybreakwhen its condition holds.
Applying it
The main signature reads async function fetchAllOrders(pageSize = 50)
The demo output is labeled (total orders fetched:), so every printed line maps back to its originating operation.
Statements that matter
const data = await client.request(query, { first: pageSize, after });
results.push(...edges.map((edge) => edge.node));
const orders = await fetchAllOrders();
Interactive Tools for This Topic
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.
FAQ
- Are there third-party dependencies?
- `graphql-request` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.