How to do pagination Node.js with MySQL ?
Last Updated :
05 Aug, 2024
Node.js is a runtime environment like Chrome's V8 JavaScript engine. Node.js is an open-source, cross-platform, and backend runtime environment that executes outside a web browser.
MySQL is an open-source relational database management system that is fast, reliable, flexible, and robust. Both MySQL and Node.js are trendy choices when building web applications. Another advantage of MySQL is its built-in support for utilities like pagination.
What is pagination, and why is it important?
Pagination is nothing but dividing data into discrete chunks or pages. A web page displaying thousands of records divided as pages feels more inviting and interactive and better for the application performance. Pagination thus helps better display, performance, and user experience by not overwhelming the user with data and avoiding long scrolling.
We can do both Client-side Pagination as well as Server-side Pagination. In this article, we will see an example of a Server-side Pagination.
Server-Side Pagination: As per IBM, Server-side Pagination is for:
- Large data set.
- Faster initial page load.
- Accessibility for those not running JavaScript.
- Complex view business logic.
- Resilience to concurrent changes.
Server-side pagination is usually done in the middleware (business logic) code or the database layer. Server-side pagination is usually more challenging than client-side, but it scales better.
Client-side Pagination: Client-side pagination is proper when:
- The Data Set is small.
- Faster subsequent page loads
- Sort & filter requirements are supported fully (unless results greater than max size).
Client-side pagination is faster to implement but is not very scalable.
Steps to do Server-side Pagination?
We are going to look at an example of Server-Side Pagination. We will handle pagination at the database level itself. For pagination using MySQL, we need to use the LIMIT Clause with the Offset value. The Limit Clause retrieves only a part of the records. The basic Syntax of the Limit clause is as follows:
Select <column-names>
From <table-names>
Where <conditions>
LIMIT <offset>, <number_of_records>;
Offset is optional with a default value of 0 but can get any positive value less than the number of records in the dataset.
Example Application: We will build a simple application with Node.js, Express.js, MySQL, and the Sequelize ORM. Ensure that you have Node.js and MySQL on your system. We will be using Visual Studio Code for developing the app.
Create a project folder and change the folder
mkdir PaginationExample
cd PaginationExample
Initialize the app
npm init
To generate the package.json file.
Next, we install express.js, sequelize, and pug for the templates.
npm install -g express sequelize pug dotenv express-paginate
We also require installing the dotenv and the express-paginate package. The Express-paginate package exposes various methods like href and middleware. The details of the functions are given in the documentation.
Our Folder structure is as follows.
Project folder structureTo run the node application, we need to run the following command from the Terminal in Visual Studio Code.
node server.js
If everything runs correctly, you should see an output similar to this in the terminal:
Running applicationOnce you see this message, you can open a browser and go to the link: localhost:8000
We have structured the calls in the application, and we should directly see a table with records and an option to Paginate.
Application Code: We will see the Application code files layer by layer.
Server.js File: The server.js is the main file that contains all your express-related configurations and our only route for fetching the records and calling the service file. The server file has the following code.
JavaScript
// Required External modules
const express = require("express");
const path = require("path");
require("dotenv").config();
const paginate = require("express-paginate");
// Required code files
const services = require("./service/services.js");
// Application Variables
const app = express();
const port = 8000;
// Server
app.listen(port, () => {
console.log(`App running on port ${port}.`);
});
// Configuration
app.set("views", path.join(__dirname, "./views"));
app.set("view engine", "pug");
app.use("/static", express.static(
path.join(__dirname, "public")));
app.use(paginate.middleware(10, 50));
// Routes
app.get("/", (req, res) => {
const limit = req.query.limit || 10;
const offset = req.offset;
services.findRecords({
offset: offset,
limit: limit
}).then((results) => {
const pageCount = Math.ceil(results.count / limit);
res.render("paginatedTable", {
data: results.rows,
pageCount,
pages: paginate.getArrayPages(req)
(3, pageCount, req.query.page),
});
});
});
Sequelize files: We have separated the database configuration, the Sequelize model, and the call into three separate files to make it easier to maintain as the application scales.
- The Services file holds all our Sequelize calls.
- The models.js holds the table structure we use for our query. We are using the nicer_but_slower_film_list table from the SAKILA database for our example.
- The dbconfig.js file holds the Sequelize object. The entire code related to files is available in this repository.
- Sequelize provides an in-built method: findAndCountAll, which is ideal for pagination. The findAndCountAll method takes the arguments offset and limit and returns the total records available and the actual records based on the limit and offset value. The code is as follows:
dbconfig.js: The dbconfig holds the Sequelize object. The properties for creating the Sequelize object come from the .env file based on your database setup. Here we have created a simple database object.
JavaScript
const Sequelize = require("sequelize");
module.exports = new Sequelize({
dialect: "mysql",
username: process.env.DB_USER,
password: process.env.DB_PASS,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
logging: (log) => console.log("logging:", log),
});
models.js: The models.js file holds the description of the tables we are using in our queries. It is a Sequelize representation of the relational database tables.
JavaScript
var Sequelize = require("sequelize");
db = require("../config/dbconfig.js");
const nicer_but_slower_film_list = db.define(
"nicer_but_slower_film_list", {
FID: {
type: Sequelize.SMALLINT,
// To ensure that Sequelize
// does not use id by default
primaryKey: true,
},
title: Sequelize.STRING,
description: Sequelize.STRING,
category: Sequelize.STRING,
price: Sequelize.DECIMAL,
length: Sequelize.SMALLINT,
rating: Sequelize.ENUM("G", "PG", "PG-13", "R", "NC-17"),
actors: Sequelize.STRING,
},
{
// This is to ensure that Sequelize
// does not pluralize table names
freezeTableName: true,
// This is to ensure that Sequelize
// does not add its own timestamp
// variables in the query.
timestamps: false,
createdAt: false,
updatedAt: false,
}
);
module.exports = nicer_but_slower_film_list;
services.js: The services file holds the Sequelize calls we perform. This file would hold the calls for search, create, update, delete calls, etc. The file depends on the Sequelize object (dbconfig.js) and the Sequelize model (models.js).
JavaScript
const Sequelize = require("sequelize");
// Model file
var model = require("../models/models.js");
// db Configuration
db = require("../config/dbconfig.js");
let findRecords = async (req, res) => {
return model.findAndCountAll({
offset: req.offset,
limit: req.limit
});
};
module.exports = { findRecords: findRecords };
So if the limit we set is ten and the offset is 20 (that is page 3 records), then the query formed by the findAndCountAll and triggered in the database is:
SELECT `FID`, `title`, `description`, `category`, `price`, `length`, `rating`, `actors` FROM `nicer_but_slower_film_list` AS `nicer_but_slower_film_list` LIMIT 20, 10;
The query gives the following results from the database:
The output shown on the screen is as follows:
Application UI: Besides the files mentioned above, the project structure also has the node_modules folder, the node and express installation files, and the .env file. The .env file contains the database-related information like the Username, Password, MySQL Port number, etc., which we use in the dbconfig.js file to build the Sequelize connection object.
User Interface: To handle the user interface, we are using the PUG template. We use the express-paginate methods to handle pagination controls in the PUG template. The following code handles whether the Previous and the Next button links are shown or not.
paginatedTable.pug: This is the user interface with paginated results.
HTML
html
head
link(rel='stylesheet' href='https://getbootstrap.com/docs/4.4/dist/css/bootstrap.min.css')
style
include ../public/style.css
body
h1 Movies
table
thead
tr
th Title
th Description
th Category
th Length
th Rating
th Actors
tbody
each dat in data
tr
td #{dat.title}
td #{dat.description}
td #{dat.category}
td #{dat.length}
td #{dat.rating}
td #{dat.actors}
if paginate.hasPreviousPages || paginate.hasNextPages(pageCount)
.navigation.well-sm#pagination
ul.pager
if paginate.hasPreviousPages
a(href=paginate.href(true)).prev
i.fa.fa-arrow-circle-left
| Previous
if pages
each page in pages
a.btn.btn-default(href=page.url)= page.number
if paginate.hasNextPages(pageCount)
a(href=paginate.href()).next
| Next
i.fa.fa-arrow-circle-right
script(src='https://code.jquery.com/jquery-3.4.1.slim.min.js')
script(src='https://getbootstrap.com/docs/4.4/dist/js/bootstrap.bundle.min.js')
hasPrevious and hasNext are two methods exposed by the express-paginate package, which return Boolean values. Depending on the value of these Booleans, The UI shows the Next and Previous buttons.
Next and Previous buttonsstyle.css
The style sheet for the page is as follows:
CSS
table {
width: 100%;
border: 1px solid #fff;
border-collapse: collapse;
border-radius: 8px;
}
th,
td {
text-align: left;
text-transform: capitalize;
border: 1px solid darkgrey;
color: black;
}
th {
padding: 8px 10px;
height: 48px;
background-color: #808e9b;
}
td {
padding: 6px 8px;
height: 40px;
}
a:hover {
background-color: #555;
}
a:active {
background-color: black;
}
a:visited {
background-color: #ccc;
}
How does the application work exactly?
- The first time we hit the URL localhost:8000, because of the express-paginate middleware, the Limit value is set to 10 by default, and the offset is set to 0. Hence the first ten records are retrieved from the database and displayed.
- When the user hits the Next button or page number, i.e., 1,2, or 3, the paginate middleware calculates the offset. The formula to calculate offset is simple:
pageNumber(we see in the URL on the UI) -1 * limit
Where pageNumber starts at 1.
- We can also increase the limit up to 50 records. We cannot increase the limit further than 50 records since we have specified that as the maximum limit in the middleware function. The limit has been set in the server.js file.
app.use(paginate.middleware(10, 50));
Triggering a query like this:: http://localhost:8000/?page=1&limit=500 will not cause an error, but the number of records displayed will still be 50. We can also enhance the functionality to show some messages that only 50 records can be seen at one time.
Summary: This article showed how pagination works with Node.js and MySQL using a sample database from MySQL. We also saw how we could limit the user to see only a set number of records on the page not to cause UI disruptions. The entire code is available on the Github link.
Similar Reads
Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Introduction & Installation
NodeJS IntroductionNodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodeJS is single-threaded, utilizing an event l
5 min read
Node.js Roadmap: A Complete GuideNode.js has become one of the most popular technologies for building modern web applications. It allows developers to use JavaScript on the server side, making it easy to create fast, scalable, and efficient applications. Whether you want to build APIs, real-time applications, or full-stack web apps
6 min read
How to Install Node.js on LinuxInstalling Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a
6 min read
How to Install Node.js on WindowsInstalling Node.js on Windows is a straightforward process, but it's essential to follow the right steps to ensure smooth setup and proper functioning of Node Package Manager (NPM), which is crucial for managing dependencies and packages. This guide will walk you through the official site, NVM, Wind
6 min read
How to Install NodeJS on MacOSNode.js is a popular JavaScript runtime used for building server-side applications. Itâs cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system.What is Node.jsNode.js is an open-source,
6 min read
Node.js vs Browser - Top Differences That Every Developer Should KnowNode.js and Web browsers are two different but interrelated technologies in web development. JavaScript is executed in both the environment, node.js, and browser but for different use cases. Since JavaScript is the common Programming language in both, it is a huge advantage for developers to code bo
6 min read
NodeJS REPL (READ, EVAL, PRINT, LOOP)NodeJS REPL (Read-Eval-Print Loop) is an interactive shell that allows you to execute JavaScript code line-by-line and see immediate results. This tool is extremely useful for quick testing, debugging, and learning, providing a sandbox where you can experiment with JavaScript code in a NodeJS enviro
5 min read
Explain V8 engine in Node.jsThe V8 engine is one of the core components of Node.js, and understanding its role and how it works can significantly improve your understanding of how Node.js executes JavaScript code. In this article, we will discuss the V8 engineâs importance and its working in the context of Node.js.What is a V8
7 min read
Node.js Web Application ArchitectureNode.js is a JavaScript-based platform mainly used to create I/O-intensive web applications such as chat apps, multimedia streaming sites, etc. It is built on Google Chromeâs V8 JavaScript engine. Web ApplicationsA web application is software that runs on a server and is rendered by a client browser
3 min read
NodeJS Event LoopThe event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It:Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network r
5 min read
Node.js Modules , Buffer & Streams
NodeJS ModulesIn NodeJS, modules play an important role in organizing, structuring, and reusing code efficiently. A module is a self-contained block of code that can be exported and imported into different parts of an application. This modular approach helps developers manage large projects, making them more scal
6 min read
What are Buffers in Node.js ?Buffers are an essential concept in Node.js, especially when working with binary data streams such as files, network protocols, or image processing. Unlike JavaScript, which is typically used to handle text-based data, Node.js provides buffers to manage raw binary data. This article delves into what
4 min read
Node.js StreamsNode.js streams are a key part of handling I/O operations efficiently. They provide a way to read or write data continuously, allowing for efficient data processing, manipulation, and transfer.\Node.js StreamsThe stream module in Node.js provides an abstraction for working with streaming data. Strea
4 min read
Node.js Asynchronous Programming
Node.js NPM
NodeJS NPMNPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.It is primarily used to manage packages or modulesâthese are
6 min read
Steps to Create and Publish NPM packagesIn this article, we will learn how to develop and publish your own npm package (also called an NPM module). There are many benefits of NPM packages, some of them are listed below: Reusable codeManaging code (using versioning)Sharing code The life-cycle of an npm package takes place like below: Modu
7 min read
Introduction to NPM scriptsNPM is a Node Package Manager. It is the world's largest Software Registry. This registry contains over 800,000 code packages. Many Open-source developers use npm to share software. Many organizations also use npm to manage private development. "npm scripts" are the entries in the scripts field of t
2 min read
Node.js package.jsonThe package.json file is the heart of Node.js system. It is the manifest file of any Node.js project and contains the metadata of the project. The package.json file is the essential part to understand, learn and work with the Node.js. It is the first step to learn about development in Node.js.What d
4 min read
What is package-lock.json ?package-lock.json is a file that is generated when we try to install the node. It is generated by the Node Package Manager(npm). package-lock.json will ensure that the same versions of packages are installed. It contains the name, dependencies, and locked version of the project. It will check that s
3 min read
Node.js Deployments & Communication
Node DebuggingDebugging is an essential part of software development that helps developers identify and fix errors. This ensures that the application runs smoothly without causing errors. NodeJS is the JavaScript runtime environment that provides various debugging tools for troubleshooting the application.What is
3 min read
How to Perform Testing in Node.js ?Testing is a method to check whether the functionality of an application is the same as expected or not. It helps to ensure that the output is the same as the required output. How Testing can be done in Node.js? There are various methods by which tasting can be done in Node.js, but one of the simple
2 min read
Unit Testing of Node.js ApplicationNode.js is a widely used javascript library based on Chrome's V8 JavaScript engine for developing server-side applications in web development. Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of
5 min read
NODE_ENV Variables and How to Use Them ?Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicate
2 min read
Difference Between Development and Production in Node.jsIn this article, we will explore the key differences between development and production environments in Node.js. Understanding these differences is crucial for deploying and managing Node.js applications effectively. IntroductionNode.js applications can behave differently depending on whether they a
3 min read
Best Security Practices in Node.jsThe security of an application is extremely important when we build a highly scalable and big project. So in this article, we are going to discuss some of the best practices that we need to follow in Node.js projects so that there are no security issues at a later point of time. In this article, we
4 min read
Deploying Node.js ApplicationsDeploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications.To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process.
5 min read
How to Build a Microservices Architecture with NodeJSMicroservices architecture allows us to break down complex applications into smaller, independently deployable services. Node.js, with its non-blocking I/O and event-driven nature, is an excellent choice for building microservices. How to Build a Microservices Architecture with NodeJS?Microservices
3 min read
Node.js with WebAssemblyWebAssembly, often abbreviated as Wasm, is a cutting-edge technology that offers a high-performance assembly-like language capable of being compiled from various programming languages such as C/C++, Rust, and AssemblyScript. This technology is widely supported by major browsers including Chrome, Fir
3 min read
Resources & Tools
Node.js Web ServerA NodeJS web server is a server built using NodeJS to handle HTTP requests and responses. Unlike traditional web servers like Apache or Nginx, which are primarily designed to give static content, NodeJS web servers can handle both static and dynamic content while supporting real-time communication.
6 min read
Node Exercises, Practice Questions and SolutionsNode Exercise: Explore interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your Node proficiency at your own pace. Start coding now! #content-iframe { width: 100%; height: 500px;} @media (max-width: 768px)
4 min read
Node.js ProjectsNode.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
9 min read
NodeJS Interview Questions and AnswersNodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read