0
0
GraphqlHow-ToBeginner · 4 min read

How to Use last and before for Pagination in GraphQL

In GraphQL, use last with before to paginate backwards by fetching the last N items before a given cursor. This helps retrieve previous pages in a connection-based pagination system using cursor-based pagination.
📐

Syntax

The last argument specifies how many items to fetch counting backwards from the cursor given by before. The before argument is a cursor that marks the point before which to fetch items.

  • last: Int - Number of items to fetch from the end.
  • before: String - Cursor to fetch items before.
graphql
query GetPreviousItems($last: Int!, $before: String!) {
  items(last: $last, before: $before) {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      hasPreviousPage
      startCursor
    }
  }
}
💻

Example

This example fetches the last 3 items before a given cursor to paginate backwards through a list of items.

graphql
query GetPreviousItems {
  items(last: 3, before: "cursor123") {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      hasPreviousPage
      startCursor
    }
  }
}
Output
{ "data": { "items": { "edges": [ {"node": {"id": "4", "name": "Item 4"}, "cursor": "cursor4"}, {"node": {"id": "5", "name": "Item 5"}, "cursor": "cursor5"}, {"node": {"id": "6", "name": "Item 6"}, "cursor": "cursor6"} ], "pageInfo": { "hasPreviousPage": true, "startCursor": "cursor4" } } } }
⚠️

Common Pitfalls

Common mistakes include:

  • Using last without before, which may return unexpected results or errors.
  • Confusing last with first which fetches items forward.
  • Not handling pageInfo.hasPreviousPage to know if more pages exist backward.

Always pair last with before to paginate backwards correctly.

graphql
query WrongPagination {
  items(last: 3) {  # Missing 'before' cursor
    edges {
      node {
        id
      }
    }
  }
}

# Correct usage:
query CorrectPagination {
  items(last: 3, before: "cursor123") {
    edges {
      node {
        id
      }
    }
  }
}
📊

Quick Reference

ArgumentPurposeUsage Notes
lastFetches the last N items before the cursorMust be used with 'before' for backward pagination
beforeCursor to fetch items beforeUsed with 'last' to paginate backwards
firstFetches the first N items after the cursorUsed with 'after' for forward pagination
afterCursor to fetch items afterUsed with 'first' to paginate forwards

Key Takeaways

Use last with before to paginate backwards in GraphQL.
Always provide a valid cursor in before when using last.
Check pageInfo.hasPreviousPage to know if more pages exist before the current set.
Do not confuse last with first; they paginate in opposite directions.
Proper cursor-based pagination improves performance and user experience.