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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
{
  "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

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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

1
2
3
4
5
6
7
// get users
// HTTP GET
 
//get users (pagination)
// HTTP GET

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