Sling Academy
Home/Node.js/How to Implement Pagination in Express JS

How to Implement Pagination in Express JS

Last updated: December 28, 2023

Overview

In web development, pagination is a crucial feature for handling the display of large datasets. It allows developers to present data in a more organized and user-friendly manner, loading a limited number of items per page. This tutorial will walk you through the process of implementing pagination in a web application using Express.js, a common backend framework for Node.js applications. We’ll start with a basic example and progressively move to more advanced techniques, covering different pagination strategies and best practices.

Basic Pagination Setup

Let’s start by setting up a basic pagination system. Firstly, install Express and any other necessary packages:

npm install express

Create a simple Express server:

const express = require('express');
const app = express();

app.listen(3000, function () {
  console.log('Server is running on port 3000');
});

Next, let’s implement a route that will handle paginated requests:

app.get('/items', (req, res) => {
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const offset = (page - 1) * limit;

  // Here you would normally retrieve the items from a database
  const items = getDataFromDatabase({ limit, offset });
  res.json({
    page,
    limit,
    totalItems: items.length,
    items,
  });
});

Advanced Pagination Features

Now that we have a basic pagination structure in place, let’s explore more advanced features like metadata provision and pagination strategies.

Adding Metadata

Providing additional metadata with your paginated response can be very useful. This might include total number of pages, the current page, or links to the next and previous pages.

// ... previous code

const totalItems = getTotalItemCountFromDatabase();
const totalPages = Math.ceil(totalItems / limit);

res.json({
  items,
  pageInfo: {
    page,
    totalPages,
    limit,
    totalItems,
    prevPage: page > 1 ? page - 1 : null,
    nextPage: page < totalPages ? page + 1 : null
  }
});

Pagination Strategies

There are different pagination strategies such as offset-based, cursor-based, and keyset pagination. Each has its own use cases and performance considerations.

For large datasets, offset-based pagination can become slow as the offset increases. In such cases, cursor or keyset pagination can be more efficient. Let’s implement cursor-based pagination:

// ... previous code

app.get('/items', (req, res) => {
  const cursor = req.query.cursor;
  const limit = parseInt(req.query.limit, 10) || 10;
  const items = getDataAfterCursor({ cursor, limit });
  const nextCursor = items.length === limit ? items[items.length - 1].id : null;

  res.json({
    items,
    nextPageCursor: nextCursor,
    limit
  });
});

Conclusion

In conclusion, pagination is an essential element of web development for creating scalable and user-friendly applications. Throughout this tutorial, we’ve learned how to implement simple offset-based pagination in Express.js, provide useful metadata, and some advanced pagination strategies that can be beneficial for performance optimization in handling large datasets. Remember that the choice of pagination strategy will largely depend on the specific requirements of your application and the nature of the data you’re dealing with.

By now, you should have a good understanding of how to add basic pagination to your applications and are ready to explore more complex implementations if needed. Happy coding!

Next Article: How to Implement a Shopping Cart in ExpressJS

Previous Article: How to Get a URL Parameter in Express

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates