JavaScript

How to do pagination in Node.js

Hello. In this tutorial, we will explain the concept of pagination in a node.js application.

1. Introduction

Pagination is a concept of adding numbers to identify the sequence of pages. In pagination, we use the skip and limit key for reducing the size of data retrieved from the database. In this tutorial, we will implement pagination in the simplest terms i.e. without the help of a database.

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

pagination in Node.js - npm installation
Fig. 1: Verifying node and npm installation

2. How to do pagination in Node.js

To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up the implementation

Let us write the different files which will be required for practical learning.

2.2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.

package.json

{
  "name": "nodejs-pagination",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2.2 Creating an index file

Add the code to the index file that will consist of the API endpoints to understand the pagination in detail. We will be using a dummy users project for a better understanding.

server.js

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

const users = [
  {
    id: 1,
    full_name: "Kendre Abelevitz"
  },
  {
    id: 2,
    full_name: "Rona Walas"
  },
  {
    id: 3,
    full_name: "Myrtle Baser"
  },
  {
    id: 4,
    full_name: "Washington Walklot"
  },
  {
    id: 5,
    full_name: "Jo De Domenici"
  },
  {
    id: 6,
    full_name: "Lief Mungham"
  },
  {
    id: 7,
    full_name: "Raquel Donlon"
  },
  {
    id: 8,
    full_name: "Vivien Wedmore."
  },
  {
    id: 9,
    full_name: "Andrei Hubach"
  },
  {
    id: 10,
    full_name: "Coral Bunney"
  },
  {
    id: 11,
    full_name: "Lanny Simco"
  },
  {
    id: 12,
    full_name: "Loralie Bransdon"
  },
  {
    id: 13,
    full_name: "Rad Aubert"
  },
  {
    id: 14,
    full_name: "Kit Branno"
  },
  {
    id: 15,
    full_name: "Quillan Bondar"
  },
  {
    id: 16,
    full_name: "Averil Dafforne"
  },
  {
    id: 17,
    full_name: "Caroljean Grattan"
  },
  {
    id: 18,
    full_name: "Abbie McCurtin"
  },
  {
    id: 19,
    full_name: "Rosalia Plowell"
  },
  {
    id: 20,
    full_name: "Juli Grieve"
  }
];

// get all results
app.get("/users", (req, res) => {
  res.json(users);
});

// get paginated results
app.get("/users/paginate", paginatedResults(users), (req, res) => {
  res.json(res.paginatedResults);
});

function paginatedResults(model) {
  // middleware function
  return (req, res, next) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);

    // calculating the starting and ending index
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;

    const results = {};
    if (endIndex < model.length) {
      results.next = {
        page: page + 1,
        limit: limit
      };
    }

    if (startIndex > 0) {
      results.previous = {
        page: page - 1,
        limit: limit
      };
    }

    results.results = model.slice(startIndex, endIndex);

    res.paginatedResults = results;
    next();
  };
}

const port = 3006;
const url = "http://localhost:" + port;
app.listen(port, () => {
  console.log("Service endpoint= %s", url);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on a port number – 3006.

pagination in Node.js - starting the app
Fig. 2: Starting the application

4. Demo

You are free to use postman or any other tool of your choice to make the HTTP request to the application endpoints.

Endpoints

// get users
// HTTP GET
http://localhost:3005/users

//get users (pagination)
// HTTP GET
http://localhost:3005/users/paginate?page=1&limit=15

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned about the pagination concepts and sample application to see how it is used practically. You can download the source code and the postman collection from the Downloads section.

6. Download the Project

This was a tutorial to implement pagination in the nodejs application.

Download
You can download the full source code of this example here: How to do pagination in Node.js

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button