Simple Node.js Express CosmosDB Pagination

I struggled to find a simple example of how I could return paginated results from an Azure CosmosDB from a Node.js Express application. Luckily, I eventually came across a brilliant article by Elio Struyf which can be found here – Retrieving the CosmosDB query continuation token in Node.js.

I’ll post my complete example of pagination from CosmosDB below and explain how it works.

The Solution

This article will assume that you’ve followed the instructions on the official Microsoft SQL Api Node.JS example app or at minimum have an existing CosmosDB and an existing Model file that can succesfully connect to the database. If you’ve not done this then check it out at the link below –

Build a Node.js web app using the JavaScript SDK to manage a SQL API account in Azure Cosmos DB

You likely have a model very similar to below that allows you to retrieve some type of result from the database, in my case this looks like the function below –

async getAll() {
        const querySpec = "SELECT * FROM root r"
        const resources = await this.find(querySpec)
        return resources;

This simply returns all records from a collection in CosmosDB that I configured at a higher level.

Returning a paginated version of the same is as simple as changing it as follows –

async getAll(continuationToken = undefined) {
        const querySpec = "SELECT * FROM root r"

        const results = await this.container.items.query(querySpec, {
            maxItemCount: 5,
            partitionKey: undefined,

        return {
            items: results.resources,
            nextPageToken: results.continuationToken

This will return 5 records at most and will not limit by any particular partition. It will also return the first page of results.

To return the second page you would use the value retrieved from the nextPageToken value as the continuationToken input. This may look as below in a simplified example –


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.