How to Page DynamoDB Query Results in AWS Emulator
DynamoDB's Query and Scan return results in pages. To read the next page, you pass the LastEvaluatedKey from the response as the ExclusiveStartKey of the next request. This is how a "Load more" button or infinite scroll fetches a few items at a time from DynamoDB. Without using an AWS account, I tested this against AWS Emulator with the AWS CLI and AWS SDK for JavaScript v3, and I show the commands and their output as they ran.
The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.556 (released November 21, 2026), AWS CLI 2.42.1, Node.js 22.23.5, and @aws-sdk/client-dynamodb and @aws-sdk/lib-dynamodb 3.1175.0. I did not use an AWS account or credentials. I did not test how paging behaves on the real DynamoDB (whether page boundaries fall in the same places, the read capacity consumed, or the pricing). Where I describe the real service, I am relying on the official documentation. I did not test a Query on a global secondary index or parallel scans (Segment). In the output, I replaced the 12-digit account ID.
- 1. Set up the emulator and a table
- 2. Pass LastEvaluatedKey as the next ExclusiveStartKey
- 3. Tell the last page by the absence of LastEvaluatedKey
- 4. Limit is the number of items evaluated, not the number returned
- 5. Without Limit, results are split at 1 MB
- 6. The AWS CLI reads to the end automatically unless you pass –limit
- 7. In the SDK, use paginateQuery or pass LastEvaluatedKey yourself
- 8. Scan is paged the same way
Set up the emulator and a table
AWS Emulator is an emulator that accepts AWS API calls locally. How to install it is covered in a separate article, "How to Install AWS Emulator on Ubuntu and Get Started." In the test environment, I installed the Debian package from the Linux instructions after verifying its gpg signature, then started it with aws-emulator -t off (-t off disables telemetry).
On the terminal where I use the AWS CLI, I point the endpoint at the emulator with the environment variables from the official documentation. I added AWS_PAGER so that output is printed directly instead of being opened in a pager.
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
export AWS_PAGER=
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
The official documentation warns that if you run a command in a shell where AWS_ENDPOINT_URL is not set, the command can be sent to the real AWS using any credentials it finds. On a machine that has real credentials, run commands only in a shell where all of the environment variables above are set.
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator
As an example, I created a table neko-diary that stores diary entries for each cat. The partition key is the cat's name (cat), and the sort key is the date (day). I loaded 12 entries for mike from November 1 to 12 and 5 entries for tama with batch-write-item. One entry looks like this, where nap is the length of the nap in hours.
$ aws dynamodb create-table --table-name neko-diary \
--attribute-definitions AttributeName=cat,AttributeType=S AttributeName=day,AttributeType=S \
--key-schema AttributeName=cat,KeyType=HASH AttributeName=day,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST --query TableDescription.TableStatus --output text
CREATING
$ aws dynamodb wait table-exists --table-name neko-diary
$ jq -c '."neko-diary"[0].PutRequest.Item' batch1.json
{"cat":{"S":"mike"},"day":{"S":"2026-11-01"},"nap":{"N":"2"}}
Pass LastEvaluatedKey as the next ExclusiveStartKey
I read mike's diary entries five at a time. With the AWS CLI, I add --limit 5. Below, to avoid repeating the same Query parts (table name, key condition, and values) each time, I abbreviate the command as aws dynamodb query .... The omitted part is:
aws dynamodb query --table-name neko-diary \
--key-condition-expression 'cat = :c' \
--expression-attribute-values '{":c":{"S":"mike"}}'
I used --query to show only the dates, the count, and LastEvaluatedKey.
$ aws dynamodb query ... --limit 5 --output json \
--query '{Days:Items[].day.S,Count:Count,ScannedCount:ScannedCount,LastEvaluatedKey:LastEvaluatedKey}'
{
"Days": [
"2026-11-01",
"2026-11-02",
"2026-11-03",
"2026-11-04",
"2026-11-05"
],
"Count": 5,
"ScannedCount": 5,
"LastEvaluatedKey": {
"day": {
"S": "2026-11-05"
},
"cat": {
"S": "mike"
}
}
}
LastEvaluatedKey is the key of the last item this call stopped reading at. The Query API reference explains that you pass this value as ExclusiveStartKey in the next call. As the name "Exclusive" suggests, the item with the passed key is not included; reading starts right after it.
$ aws dynamodb query ... --limit 5 \
--exclusive-start-key '{"cat":{"S":"mike"},"day":{"S":"2026-11-05"}}' \
--output json --query '{Days:Items[].day.S,Count:Count,LastEvaluatedKey:LastEvaluatedKey}'
{
"Days": [
"2026-11-06",
"2026-11-07",
"2026-11-08",
"2026-11-09",
"2026-11-10"
],
"Count": 5,
"LastEvaluatedKey": {
"cat": {
"S": "mike"
},
"day": {
"S": "2026-11-10"
}
}
}
$ aws dynamodb query ... --limit 5 \
--exclusive-start-key '{"cat":{"S":"mike"},"day":{"S":"2026-11-10"}}' \
--output json --query '{Days:Items[].day.S,Count:Count,LastEvaluatedKey:LastEvaluatedKey}'
{
"Days": [
"2026-11-11",
"2026-11-12"
],
"Count": 2,
"LastEvaluatedKey": null
}
The third page has 2 items and no LastEvaluatedKey (the --query pulled it out, so it shows as null). This is the last page.

Tell the last page by the absence of LastEvaluatedKey
You cannot tell whether a page is the last one from its item count alone. When I read from after 2026-11-08 with --limit 4 (this corresponds to the third page when reading 12 items four at a time), I got exactly 4 items, and a LastEvaluatedKey was still returned.
$ aws dynamodb query ... --limit 4 \
--exclusive-start-key '{"cat":{"S":"mike"},"day":{"S":"2026-11-08"}}' \
--output json --query '{Days:Items[].day.S,Count:Count,LastEvaluatedKey:LastEvaluatedKey}'
{
"Days": [
"2026-11-09",
"2026-11-10",
"2026-11-11",
"2026-11-12"
],
"Count": 4,
"LastEvaluatedKey": {
"day": {
"S": "2026-11-12"
},
"cat": {
"S": "mike"
}
}
}
$ aws dynamodb query ... --limit 4 \
--exclusive-start-key '{"cat":{"S":"mike"},"day":{"S":"2026-11-12"}}' --output json
{
"Items": [],
"Count": 0,
"ScannedCount": 0
}
When I read further, the response had 0 items and no LastEvaluatedKey. The API reference also says that a LastEvaluatedKey does not guarantee more data, and that you have reached the end only when LastEvaluatedKey is empty. If you decide whether to show a "Load more" button based on LastEvaluatedKey, pressing it can sometimes add nothing.
To read everything in a shell script, repeat until LastEvaluatedKey is gone. The following fetch-all.sh uses jq to extract LastEvaluatedKey and pass it to the next call.
#!/bin/bash
# fetch-all.sh: read until LastEvaluatedKey is gone, using --limit and --exclusive-start-key
start=()
page=0
while :; do
page=$((page + 1))
aws dynamodb query --table-name neko-diary \
--key-condition-expression 'cat = :c' \
--expression-attribute-values '{":c":{"S":"mike"}}' \
--limit 5 "${start[@]}" --output json > page.json
echo "ページ$page: $(jq -r '[.Items[].day.S] | join(" ")' page.json)"
last=$(jq -c '.LastEvaluatedKey // empty' page.json)
[ -z "$last" ] && break
start=(--exclusive-start-key "$last")
done
$ bash fetch-all.sh
ページ1: 2026-11-01 2026-11-02 2026-11-03 2026-11-04 2026-11-05
ページ2: 2026-11-06 2026-11-07 2026-11-08 2026-11-09 2026-11-10
ページ3: 2026-11-11 2026-11-12
Limit is the number of items evaluated, not the number returned
Limit is not the maximum number of items returned per call. The API reference describes it as "the maximum number of items to evaluate (not necessarily the number of matching items)." The difference shows up when you combine it with a filter expression (--filter-expression). This is the result of trying to fetch 5 items at a time for only the days when the nap was 5 hours or longer. In this command, I replaced the omitted --expression-attribute-values with one that adds :n.
$ aws dynamodb query ... --limit 5 --filter-expression 'nap >= :n' \
--expression-attribute-values '{":c":{"S":"mike"},":n":{"N":"5"}}' --output json \
--query '{Items:Items[].[day.S,nap.N],Count:Count,ScannedCount:ScannedCount,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Items": [
[
"2026-11-04",
"5"
],
[
"2026-11-05",
"6"
]
],
"Count": 2,
"ScannedCount": 5,
"LastEvaluatedKey": "2026-11-05"
}
It evaluated 5 items (ScannedCount is 5) and returned only the 2 that matched the condition (Count is 2). The official Query pagination description also says that a filter expression is applied after the limit, so a page can include a LastEvaluatedKey even when no items match. If you always need 5 items per screen, either keep reading and combine results until you have 5, or design the table so the key condition alone narrows the results and no filter expression is needed.
To read the newest entries first, add --no-scan-index-forward (ScanIndexForward: false in the SDK). Paging works the same way: passing LastEvaluatedKey returns the earlier dates that follow.
$ aws dynamodb query ... --limit 3 --no-scan-index-forward --output json \
--query '{Days:Items[].day.S,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Days": [
"2026-11-12",
"2026-11-11",
"2026-11-10"
],
"LastEvaluatedKey": "2026-11-10"
}
$ aws dynamodb query ... --limit 3 --no-scan-index-forward \
--exclusive-start-key '{"cat":{"S":"mike"},"day":{"S":"2026-11-10"}}' --output json \
--query '{Days:Items[].day.S,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Days": [
"2026-11-09",
"2026-11-08",
"2026-11-07"
],
"LastEvaluatedKey": "2026-11-07"
}
Without Limit, results are split at 1 MB
The official documentation says that a single Query reads up to 1 MB. Even without Limit, results are split into pages when the data is large. To check this, I loaded 15 items for a cat named kuro, each with a 100,000-character attribute photo (about 100 KB per item). I added --no-paginate so the AWS CLI would not read the remaining pages automatically, and looked at just the first call. (Automatic reading is covered in the next section.)
$ aws dynamodb query --table-name neko-diary --key-condition-expression 'cat = :c' \
--expression-attribute-values '{":c":{"S":"kuro"}}' --no-paginate --output json \
--query '{Count:Count,ScannedCount:ScannedCount,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Count": 11,
"ScannedCount": 11,
"LastEvaluatedKey": "photo-11"
}
It stopped after 11 of the 15 items and returned a LastEvaluatedKey. When I read the rest with --exclusive-start-key, the remaining 4 items came back and no LastEvaluatedKey was returned.
The first call still stopped at the same 11 items when I narrowed the output with --projection-expression to return only the key, and also when I used --select COUNT to only count the items.
$ aws dynamodb query --table-name neko-diary --key-condition-expression 'cat = :c' \
--expression-attribute-values '{":c":{"S":"kuro"}}' \
--projection-expression '#d' --expression-attribute-names '{"#d":"day"}' \
--no-paginate --output json --query '{Count:Count,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Count": 11,
"LastEvaluatedKey": "photo-11"
}
$ aws dynamodb query --table-name neko-diary --key-condition-expression 'cat = :c' \
--expression-attribute-values '{":c":{"S":"kuro"}}' --select COUNT \
--no-paginate --output json --query '{Count:Count,LastEvaluatedKey:LastEvaluatedKey.day.S}'
{
"Count": 11,
"LastEvaluatedKey": "photo-11"
}
So reducing the returned data does not change the 1 MB limit, which is counted by the size of the items read. The API reference for Limit also says that the operation stops once it has processed more than 1 MB of data. So when counting items, you need to keep reading until LastEvaluatedKey is gone and add up the Count of each page. The Scan description likewise says that when results exceed 1 MB, Count covers only some of the items, so you must add the totals yourself.
Also, day is a DynamoDB reserved word. Writing --projection-expression 'day' produced a ValidationException (reserved keyword: day). That is why the example above uses the placeholder #d.
The AWS CLI reads to the end automatically unless you pass –limit
Without any options, the AWS CLI keeps calling Query automatically until LastEvaluatedKey is gone, and prints all the results together (Query pagination description). When I removed --no-paginate and counted kuro with --select COUNT, the AWS CLI also read the remaining pages, so Count was 15 and NextToken was null.
Counting the requests in --debug output showed that with --limit, as above, Query ran only once, and the AWS CLI printed LastEvaluatedKey as is. With --page-size 5 instead of --limit, it called Query three times, 5 items per call, and printed all 12 items together.
$ aws dynamodb query ... --page-size 5 --output json \
--query '{Items:length(Items),Count:Count,ScannedCount:ScannedCount,NextToken:NextToken}'
{
"Items": 12,
"Count": 12,
"ScannedCount": 12,
"NextToken": null
}
$ aws dynamodb query ... --page-size 5 --debug 2>&1 | grep -c 'Making request for OperationModel(name=Query)'
3
As the AWS CLI pagination description says, --page-size only changes how many items each call fetches; it does not change the output.
To display a few items at a time with the AWS CLI, use --max-items and --starting-token. With --max-items 5, I got 5 items and a NextToken. Passing that NextToken to --starting-token returned the next items.
$ aws dynamodb query ... --max-items 5 --output json > p1.json
$ jq -c '{Days:[.Items[].day.S],Count:.Count,NextToken:.NextToken}' p1.json
{"Days":["2026-11-01","2026-11-02","2026-11-03","2026-11-04","2026-11-05"],"Count":12,"NextToken":"eyJFeGNsdXNpdmVTdGFydEtleSI6IG51bGwsICJib3RvX3RydW5jYXRlX2Ftb3VudCI6IDV9"}
$ jq -r .NextToken p1.json | base64 -d; echo
{"ExclusiveStartKey": null, "boto_truncate_amount": 5}
$ aws dynamodb query ... --max-items 5 --starting-token $(jq -r .NextToken p1.json) --output json \
--query '{Days:Items[].day.S,Count:Count,NextToken:NextToken}'
{
"Days": [
"2026-11-06",
"2026-11-07",
"2026-11-08",
"2026-11-09",
"2026-11-10"
],
"Count": 12,
"NextToken": "eyJFeGNsdXNpdmVTdGFydEtleSI6IG51bGwsICJib3RvX3RydW5jYXRlX2Ftb3VudCI6IDEwfQ=="
}
Although only 5 items were displayed, Count was 12. Decoding the NextToken with base64 showed that ExclusiveStartKey was null and that the token meant "drop the first 5 items." With --max-items 5 alone, the AWS CLI called Query once, received all 12 items, and cut the display to 5. The second NextToken also had ExclusiveStartKey set to null and meant "drop the first 10 items." The NextToken is a value the AWS CLI creates, and it is different from DynamoDB's LastEvaluatedKey.
When both are given, as in --page-size 5 --max-items 7, the NextToken contains an ExclusiveStartKey, and the next read resumes from the 6th item. However, the AWS CLI pagination description warns that if --page-size and --max-items use different numbers, items can be skipped or repeated, and recommends using the same number for both.
In the SDK, use paginateQuery or pass LastEvaluatedKey yourself
AWS SDK for JavaScript v3 provides paginators that read pages in sequence. The @aws-sdk/lib-dynamodb README recommends a for await loop over paginateScan, and explains that internally it does the same thing as a loop using LastEvaluatedKey. Here I used paginateQuery, the Query version, with pageSize: 5.
To connect from Node.js to the emulator, in addition to the environment variables above, set NODE_EXTRA_CA_CERTS to the emulator's certificate (export NODE_EXTRA_CA_CERTS=~/.aws/emulator/9297/ca.pem). This is covered in more detail in a separate article, "How to Use AWS Emulator from the Node.js SDK." I wrote the code in TypeScript and ran it with Node.js's feature that strips type annotations and runs .ts files directly. I did not run a type check. package.json contains "type": "module".
// paginate.ts: read every 5-item page to the end with paginateQuery
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, paginateQuery } from '@aws-sdk/lib-dynamodb';
const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const pages = paginateQuery(
{ client: doc, pageSize: 5 },
{
TableName: 'neko-diary',
KeyConditionExpression: 'cat = :c',
ExpressionAttributeValues: { ':c': 'mike' },
},
);
let n = 0;
for await (const page of pages) {
n += 1;
const days = (page.Items ?? []).map((item) => item.day);
console.log(`ページ${n}: ${page.Count}件`, days.join(' '), '次の開始キー:', page.LastEvaluatedKey?.day ?? 'なし');
}
$ node paginate.ts
ページ1: 5件 2026-11-01 2026-11-02 2026-11-03 2026-11-04 2026-11-05 次の開始キー: 2026-11-05
ページ2: 5件 2026-11-06 2026-11-07 2026-11-08 2026-11-09 2026-11-10 次の開始キー: 2026-11-10
ページ3: 2件 2026-11-11 2026-11-12 次の開始キー: なし
When an API like a list screen returns one page per request and the client reads the next page with another request, turn LastEvaluatedKey into a string (a cursor) and hand it to the client. In the following cursor.ts, I convert LastEvaluatedKey to JSON, encode it as base64url, and decode the cursor it receives back into ExclusiveStartKey. This example reads the newest diary entries 5 at a time.
// cursor.ts: turn LastEvaluatedKey into a string and read the next page in a separate request
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb';
const doc = DynamoDBDocumentClient.from(new DynamoDBClient({}));
type Page = { days: string[]; next: string | null };
async function listDiary(cat: string, cursor?: string): Promise<Page> {
const out = await doc.send(new QueryCommand({
TableName: 'neko-diary',
KeyConditionExpression: 'cat = :c',
ExpressionAttributeValues: { ':c': cat },
ScanIndexForward: false,
Limit: 5,
ExclusiveStartKey: cursor ? JSON.parse(Buffer.from(cursor, 'base64url').toString()) : undefined,
}));
const next = out.LastEvaluatedKey
? Buffer.from(JSON.stringify(out.LastEvaluatedKey)).toString('base64url')
: null;
return { days: (out.Items ?? []).map((item) => item.day), next };
}
let page = await listDiary('mike');
console.log(JSON.stringify(page));
while (page.next) {
page = await listDiary('mike', page.next);
console.log(JSON.stringify(page));
}
// What happens when a cursor made from another cat's key is passed in
const other = Buffer.from(JSON.stringify({ cat: 'tama', day: '2026-11-03' })).toString('base64url');
try {
await listDiary('mike', other);
} catch (e) {
console.log((e as Error).name + ': ' + (e as Error).message);
}
$ node cursor.ts
{"days":["2026-11-12","2026-11-11","2026-11-10","2026-11-09","2026-11-08"],"next":"eyJkYXkiOiIyMDI2LTExLTA4IiwiY2F0IjoibWlrZSJ9"}
{"days":["2026-11-07","2026-11-06","2026-11-05","2026-11-04","2026-11-03"],"next":"eyJjYXQiOiJtaWtlIiwiZGF5IjoiMjAyNi0xMS0wMyJ9"}
{"days":["2026-11-02","2026-11-01"],"next":null}
ValidationException: The provided starting key is outside query boundaries based on provided conditions
$ echo eyJkYXkiOiIyMDI2LTExLTA4IiwiY2F0IjoibWlrZSJ9 | base64 -d; echo
{"day":"2026-11-08","cat":"mike"}
base64url is not encryption, so decoding a cursor shows the key values as they are. For a table whose keys contain values you do not want to expose, such as a user ID, do not pass the raw key to the client.
As the last line shows, passing a tama key to a Query on mike produced a ValidationException. On the emulator, passing a key without a sort key produced The provided starting key is invalid. Passing a date that does not exist (2026-11-03x) did not produce an error; the response started from 2026-11-04, the next date after that position. Since a cursor received from a client may be modified, decide in advance how to handle errors (for example, returning to the first page).
Scan is paged the same way
Scan uses LastEvaluatedKey and ExclusiveStartKey in the same way (Scan pagination description). In the test environment, one --no-paginate Scan of the whole table (12 items for mike, 5 for tama, 15 for kuro) stopped at 28 items and returned a LastEvaluatedKey (photo-11 for kuro). Here too, the results were split at 1 MB. When I removed --no-paginate and counted with --select COUNT, the AWS CLI read the remaining pages, and Count was 32.
When you are finished with the table, you can delete it with aws dynamodb delete-table --table-name neko-diary. In the test environment, after waiting for it to disappear with aws dynamodb wait table-not-exists, the count from list-tables was 0.
How closely the emulator matches the real service varies by service and feature. The official fidelity documentation explains how this is measured. The same page says that per-service scores will be published for each release. The number of items per page depends on item size, so even on the real DynamoDB, the safest code does not rely on page boundaries and instead reads until LastEvaluatedKey is gone.





