GraphQL Request Cursor Pagination

Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.

JavascriptData Fetching

Code

javascriptsnippet
32 lines
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.hasNextPage short-circuits the flow with an early break when 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

FAQ

Are there third-party dependencies?
`graphql-request` — install it with the package manager before running.