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
lastwithoutbefore, which may return unexpected results or errors. - Confusing
lastwithfirstwhich fetches items forward. - Not handling
pageInfo.hasPreviousPageto 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
| Argument | Purpose | Usage Notes |
|---|---|---|
| last | Fetches the last N items before the cursor | Must be used with 'before' for backward pagination |
| before | Cursor to fetch items before | Used with 'last' to paginate backwards |
| first | Fetches the first N items after the cursor | Used with 'after' for forward pagination |
| after | Cursor to fetch items after | Used 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.