
When you visit a movie website and you notice page numbers at the bottom? Something like 1, 2, 3, 4, and so on.
- When you click on Page 1, you see one set of movies.
- When you click on Page 2, a completely different set of movies appears.
How does the website know which movies to display?
How does the frontend ask the backend for a particular set of data?
This is exactly what we are going to understand in this blog.
-
We will learn how to implement pagination using JavaScript, Node.js and Express.js by building a simple movie application.
-
We will take an example of 30 movies in our backend, but instead of showing all 30 together, we will display only 10 movies per page.
And the best part? We don't need a database to understand this concept. We can implement the complete pagination functionality using a simple JavaScript array.
So, let's get started.
1. What Is Pagination?
Before writing the code, let's first understand what pagination means.
Suppose we are building a movie website and we have 30 movies available.
Now, we want to display these movies in groups of 10.
Our requirement is quite simple:
| Page Number | Movies Displayed | Array Indexes |
|---|---|---|
| Page 1 | Movies 1–10 | 0–9 |
| Page 2 | Movies 11–20 | 10–19 |
| Page 3 | Movies 21–30 | 20–29 |
When a user clicks on Page 1, our application should display the first 10 movies.
When they click on Page 2, it should display the next 10 movies.
Similarly, clicking on Page 3 should display the remaining 10 movies.
This is what we call pagination.
Now you might ask, why do we even need pagination?

Imagine an e-commerce website with 10,000 products. If we try to fetch and display all the products together, we may end up transferring a lot of unnecessary data. It can also make the page slower and difficult to navigate.

Instead, we can fetch a smaller number of records at a time.
This helps us manage large amounts of data and gives users a better browsing experience.
You will find pagination on almost every major e-commerce website, job portal, movie platform and many other web applications.
Now let's see how we can implement it.
2. Setting Up Our Express.js Project
For this project, we will use a simple frontend and backend setup.
Our backend will be written in Express.js, and our frontend will use HTML, CSS and Vanilla JavaScript.
The project structure will look something like this:
movie-pagination/
│
├── app.js
├── movie.js
├── package.json
│
└── public/
├── index.html
├── style.css
└── script.js
Here:
app.jscontains our Express.js backend.movie.jscontains the movie data.index.htmlcontains the frontend structure.style.cssis used to style our movie cards.script.jshandles button clicks and API requests.
Creating the Express.js server
Let's start with the backend.
Inside our app.js file, we have:
const path = require("path");
const express = require("express");
const app = express();
const PORT = 4444;
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
Let's understand what's happening here.
First, we import path and express.
Then we create our Express application using:
const app = express();
We are running our server on port 4444.
Next, we have added a few middlewares.
express.urlencoded() helps us handle URL-encoded form data.
express.json() helps us read JSON request bodies.
And:
app.use(express.static(path.join(__dirname, "public")));
This line tells Express to serve the files present inside our public folder.
So, when we visit http://localhost:4444, our frontend application can load.
Our initial setup is ready.
3. Creating Our Movie Dataset
Now we need some data to implement pagination.
Since we are not using a database, we will store our movies in a JavaScript array.
I have created a file called movie.js containing 30 movies.
Each movie is represented as a JavaScript object.
Here is a small part of our actual dataset:
const movies = [
{
id: 1,
title: "The Shawshank Redemption",
genre: "Drama",
releaseYear: 1994,
rating: 9.3,
language: "English",
poster: "https://images.metahub.space/poster/medium/tt0111161/img",
},
{
id: 2,
title: "The Godfather",
genre: "Crime",
releaseYear: 1972,
rating: 9.2,
language: "English",
poster: "https://images.metahub.space/poster/medium/tt0068646/img",
},
{
id: 3,
title: "The Dark Knight",
genre: "Action",
releaseYear: 2008,
rating: 9.0,
language: "English",
poster: "https://images.metahub.space/poster/medium/tt0468569/img",
},
// ... remaining 27 movies
];
module.exports = movies;
Our complete array has 30 movies, including Inception, Interstellar, Avengers: Endgame, 3 Idiots, Dangal, RRR and many more.
Every movie contains details such as its title, genre, release year, rating, language and poster URL.
At the end of the file, we export the array using:
module.exports = movies;
Why are we doing this?
Because we want to use these movies inside our Express.js application.
So, inside app.js, we can import them using:
const allMovies = require('./movie');
Now our backend has access to all 30 movies.
And we can start working on our pagination logic.
4. Understanding the JavaScript slice() Method
Before implementing pagination, there is one important JavaScript method that we should understand.
It is called slice().
This method is going to make our pagination logic very simple.
Let's understand it with an example.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
We have an array containing numbers from 1 to 10.
As we know, JavaScript arrays follow zero-based indexing.
This means the first element is at index 0 and the last element is at index 9.
Now suppose I want to pick only a few elements from this array.
I can write:
console.log(arr.slice(1, 3));
Output:
[2, 3]
Now notice something interesting.
We passed 1 and 3, but we only got two elements.
Why?
Because the slice() method includes the starting index but excludes the ending index.
So, when we write:
arr.slice(1, 3);
JavaScript starts picking elements from index 1 and stops just before index 3.
Let's take another example:
console.log(arr.slice(0, 5));
Output:
[1, 2, 3, 4, 5]
Similarly:
console.log(arr.slice(5, 10));
Output:
[6, 7, 8, 9, 10]
See how easily we can pick different portions of the same array?
This is exactly what we want to do with our movies.
For Page 1, we want the first 10 movies.
For Page 2, we want the next 10.
And the same logic should continue for the remaining pages.
So, we just need to calculate the correct starting and ending indexes.
5. Understanding Page, Limit, Start Index and End Index
There are two important values that we need:
Page: The page number requested by the user.
Limit: The number of records we want to display on each page.
In our application, we have decided that each page will display 10 movies.
So our limit will be:
let limit = 10;
Now, suppose the user requests Page 1.
We need to start from index 0 and pick 10 movies.
If they request Page 2, we need to start from index 10.
Similarly, for Page 3, we need to start from index 20.
But we cannot write separate conditions for every page.
Imagine having 100 pages. Are we going to write 100 if-else conditions?
Of course not.
We need a formula that works for every page.
Calculating the starting index
The formula is:
let si = (page - 1) * 10;
Here, si represents the starting index.
Let's understand how it works.
For Page 1:
si = (1 - 1) * 10
si = 0
For Page 2:
si = (2 - 1) * 10
si = 10
For Page 3:
si = (3 - 1) * 10
si = 20
This means:
- Page 1 starts from index 0.
- Page 2 starts from index 10.
- Page 3 starts from index 20.
And our formula automatically works for the next pages as well.
Calculating the ending index
Now finding the ending index is even easier.
We simply add our limit to the starting index.
let ei = si + limit;
For Page 1:
si = 0
ei = 0 + 10 = 10
For Page 2:
si = 10
ei = 10 + 10 = 20
For Page 3:
si = 20
ei = 20 + 10 = 30
Remember that slice() excludes the ending index.
So when we write slice(0, 10), it picks elements from index 0 to index 9.
That gives us exactly 10 movies.
And that's the main logic behind pagination.
6. Writing Our Pagination Function
Now that we understand the formula, let's put everything together.
Inside our app.js file, we create a function called pagination().
This is the same pagination function used in our project:
function pagination(movies, page = 1){
let limit = 10;
let si = (page-1)*10;
let ei = si+limit;
return movies.slice(si, ei);
}
Let's understand this function.
First, we are accepting two parameters:
movies contains the complete movie array.
page contains the page number requested by the user.
We have also given page a default value of 1.
This means that if the function is called without a page argument, it will use Page 1.
Next, we set the limit to 10.
Using the page number, we calculate the starting index and ending index.
Finally, we return:
return movies.slice(si, ei);
That's it.
Our pagination function is ready.
For example:
pagination(allMovies, 1);
This will return the first 10 movies.
pagination(allMovies, 2);
This will return movies 11 to 20.
And:
pagination(allMovies, 3);
This will return movies 21 to 30.
Now we need to connect this function with an Express.js API.
7. Creating a Pagination API in Express.js
We have our movies array.
We also have our pagination function.
Now we need a way for the frontend to tell our backend which page it wants.
For this, we will use query parameters.
Let's say our frontend makes a request to:
http://localhost:4444/movies?page=1
Here, page=1 tells the backend that we want the first page.
Similarly:
http://localhost:4444/movies?page=2
This means we want the second page.
Now let's create our API.
Inside app.js, we have:
app.get('/movies',(req,res)=>{
const {page} = req.query;
let filteredMovies = pagination(allMovies, page);
res.send(filteredMovies);
})
Let's understand what is happening here.
Getting the page number
First, we have:
const {page} = req.query;
Express provides query parameters through req.query.
So, if we receive a request like:
/movies?page=2
The value of page will be "2".
One important thing to understand is that query parameter values are normally strings.
However, in our pagination function, JavaScript automatically converts this numeric string into a number when we perform the subtraction.
That is why our current implementation works.
Getting the required movies
Next, we call:
let filteredMovies = pagination(allMovies, page);
We pass the complete movie array and the requested page number to our pagination function.
The function calculates the indexes and returns only those movies that belong to the selected page.
Sending the response
Finally, we write:
res.send(filteredMovies);
This sends the filtered movie array back to the frontend. Express serializes the array as a JSON response.
Now let's test our API.
If we open:
http://localhost:4444/movies?page=1
We should receive the first 10 movies, starting from The Shawshank Redemption and ending with Titanic.
If we open:
http://localhost:4444/movies?page=2
We should receive movies 11 to 20, starting with Avatar and ending with The Batman.
And for:
http://localhost:4444/movies?page=3
We should receive movies 21 to 30, starting with 3 Idiots and ending with Andhadhun.
Our backend pagination is now working.
8. Complete Backend Code
Now let's look at our complete app.js file.
This combines the actual backend setup, pagination function and API used in the video.
const path = require("path");
const express = require("express");
const app = express();
const PORT = 4444;
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
const allMovies = require('./movie');
function pagination(movies, page = 1){
let limit = 10;
let si = (page-1)*10;
let ei = si+limit;
return movies.slice(si, ei);
}
app.get('/movies',(req,res)=>{
const {page} = req.query;
let filteredMovies = pagination(allMovies, page);
res.send(filteredMovies);
})
app.listen(PORT, () => {
console.log(`http://localhost:` + PORT);
});
See, the complete backend pagination logic is quite small.
We don't need hundreds of lines of code to implement it.
The important part is understanding how the starting and ending indexes are calculated.
Once that concept is clear, the rest becomes simple.
For this tutorial, we are keeping the API basic. In a production application, we should also validate the query parameters so that invalid page numbers do not produce unexpected results.
9. Connecting Pagination Buttons with the Backend
Now our backend is returning the correct movies.
But we don't want users to manually type URLs like /movies?page=1 or /movies?page=2.
We want them to click on pagination buttons.
So, let's create three buttons in our frontend.
<div class="button-group">
<button>1</button>
<button>2</button>
<button>3</button>
</div>
<div id="movieList"></div>
Now when the user clicks Button 1, we need to fetch Page 1.
When they click Button 2, we need to fetch Page 2.
One approach is to select every button separately and attach event listeners.
But there is a problem with this approach.
What if we have 10 buttons?
Or 50 buttons?
We cannot keep writing the same code again and again.
So let's use a better approach.
10. Using Event Delegation in JavaScript
Here we will use a very useful JavaScript concept called event delegation.
Instead of adding an event listener to every button, we can attach a single event listener to their parent container.
Let's select our parent element.
const buttonGroup = document.querySelector(".button-group");
Now we can add a click event listener.
buttonGroup.addEventListener("click", (event) => {
console.log(event.target.innerText);
});
Here, event.target tells us which element was clicked.
And innerText gives us the text written inside that element.
So if someone clicks Button 1, we get 1.
If someone clicks Button 2, we get 2.
And similarly, clicking Button 3 gives us 3.
Now think about it.
Instead of attaching three different event listeners, we are handling all the buttons through a single listener.
This makes our code easier to manage.
And even if we add more buttons later, the same listener can handle them.
That's the benefit of event delegation.
11. Fetching the Selected Page Using the Fetch API
Now comes the interesting part.
We know which button the user clicked.
We also have an API that accepts a page number.
So now we just need to send a request from the frontend to the backend.
For this, we will use the JavaScript Fetch API.
buttonGroup.addEventListener("click", (event) => {
if (!event.target.matches("button")) return;
fetch(`/movies?page=${event.target.innerText}`)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
});
Let's understand this.
When a user clicks on a button, we first check that the clicked element is a button.
Then we get its text using:
event.target.innerText
Suppose the user clicked Button 2.
Our fetch request will become:
fetch('/movies?page=2')
Now this request goes to our Express.js backend.
The backend receives Page 2, calls our pagination function and returns movies 11 to 20.
Then we convert the response into JavaScript data using:
response.json()
Finally, we print the received movies in the console.
If we click Button 1, we get movies 1 to 10.
If we click Button 2, we get movies 11 to 20.
And if we click Button 3, we get movies 21 to 30.
So our frontend and backend are now communicating properly.
But we still have one thing left.
We are printing the movies in the console. We want to display them on our actual webpage.
12. Displaying Movies on the Frontend Using DOM Manipulation
Now that we are receiving the correct movies, let's display them as cards.
Our movie objects already contain useful information such as:
- Movie title
- Genre
- Release year
- Rating
- Language
- Poster URL
So we can create a simple movie card showing these details.
We can use DOM manipulation to do this.
Here is an example rendering function using the same movie data structure as our project:
const movieList = document.getElementById("movieList");
function renderMovies(movies) {
movieList.replaceChildren();
movies.forEach((movie) => {
const card = document.createElement("div");
card.classList.add("movie-card");
const poster = document.createElement("img");
poster.src = movie.poster;
poster.alt = movie.title;
const title = document.createElement("h3");
title.innerText = movie.title;
const details = document.createElement("p");
details.innerText =
`${movie.genre} | ${movie.releaseYear}`;
const rating = document.createElement("p");
rating.innerText = `Rating: ${movie.rating}`;
card.appendChild(poster);
card.appendChild(title);
card.appendChild(details);
card.appendChild(rating);
movieList.appendChild(card);
});
}
Let's understand what this function does.
First, we select the movieList element from our HTML.
Then inside renderMovies(), we use:
movieList.replaceChildren();
This removes the existing movie cards.
Why is this important?
Because when someone switches from Page 1 to Page 2, we don't want the new movies to get added below the previous movies.
We want to replace them.
After clearing the old content, we loop through the movies array.
For every movie, we create a card, add the poster, title and other details, and append it to our webpage.
Now we just need to call this function after receiving our API response.
buttonGroup.addEventListener("click", (event) => {
if (!event.target.matches("button")) return;
fetch(`/movies?page=${event.target.innerText}`)
.then((response) => response.json())
.then((data) => {
renderMovies(data);
});
});
That's it.
Now our page will update whenever the user clicks on a pagination button.
To display the first page when the application initially opens, we can also make a request for Page 1 and pass that response to renderMovies().
Our basic movie pagination application is now ready.
13. Using ChatGPT to Improve Our Frontend Design
Now, one interesting thing we also explored in the video was using AI to help with frontend development.
We have already implemented our main pagination functionality.
Our backend is working, our API is returning the correct data, and our frontend is able to display movies.
But maybe our movie cards don't look that good.
We might want a better layout, proper spacing, responsive design and a more attractive UI.
Of course, we can write the complete HTML, CSS and JavaScript ourselves.
But if our main focus is learning backend pagination, we can also take the help of AI tools like ChatGPT for the frontend design.
For example, we can give a prompt like this:
I am receiving an array of movies from my Express.js backend. Each movie has an id, title, genre, releaseYear, rating, language and poster. Create a responsive movie card grid using Vanilla JavaScript, DOM manipulation and CSS. The cards should update whenever a new array of movies is received.
We can also specify the colours, layout, number of columns and card design.
But there is something important I want you to understand here.
You should never blindly copy and paste AI-generated code.
For example, in our application, the movie container is called movieList.
But what if ChatGPT generates code that looks for an element called movieGrid?
That code will not work unless we update the selector or our HTML.
Similarly, our dataset has a property called poster.
If the generated code expects posterUrl instead, we will need to make changes.
These are small things, but they matter.
So always understand the code that AI generates and make sure it matches your application.
AI can definitely help us save time, but understanding the code is still our responsibility.
14. Making Our Pagination More Flexible
Now let me give you a small task.
Till now, our pagination function has a fixed limit of 10.
let limit = 10;
But what if we want to display only 5 movies per page?
Or maybe 15 movies?
Can we make our API accept both the page number and the limit?
Yes, we can.
For example, we can send a request like:
/movies?page=1&limit=5
Here, we are requesting the first page with only 5 movies.
Similarly:
/movies?page=2&limit=15
This means we want the second page, with 15 movies per page.
To support this, we can modify our pagination function.
function pagination(movies, page = 1, limit = 10) {
let si = (page - 1) * limit;
let ei = si + limit;
return movies.slice(si, ei);
}
Notice the small change.
Earlier, we were multiplying the page number by 10.
Now, instead of using a fixed number, we are using the limit parameter.
This makes our function more flexible.
We can also update our API to accept both values.
app.get('/movies', (req, res) => {
const page = Number(req.query.page ?? 1);
const limit = Number(req.query.limit ?? 10);
if (
!Number.isInteger(page) ||
!Number.isInteger(limit) ||
page < 1 ||
limit < 1
) {
return res.status(400).json({
error: "Invalid page or limit"
});
}
let filteredMovies = pagination(
allMovies,
page,
limit
);
res.send(filteredMovies);
});
This is an additional improvement to the original video code. It also checks whether the requested page and limit are valid positive integers.
Now we can request different numbers of movies depending on our requirement.
Try implementing this yourself.
You can even add a dropdown on the frontend where users can choose whether they want to display 5, 10 or 15 movies per page.
It is a good exercise to test whether you have understood the concept properly.
15. How Does Pagination Work? Let's Revise
Now let's quickly revise the complete process.
Step 1: The user clicks a pagination button.
Step 2: JavaScript identifies the selected page number using event delegation.
Step 3: The frontend sends a GET request to our Express.js backend.
For example:
GET /movies?page=2
Step 4: Express reads the page number from req.query.
Step 5: Our pagination function calculates the starting and ending indexes.
For Page 2:
let si = (2 - 1) * 10; // 10
let ei = si + 10; // 20
Step 6: We use slice() to select the required movies.
movies.slice(10, 20);
Step 7: The backend sends these movies to the frontend.
Step 8: The frontend uses DOM manipulation to display the movie cards.
And that's how our complete pagination functionality works.
One thing to remember is that we are currently working with a JavaScript array.
In real-world applications, we generally store data in databases like MongoDB or PostgreSQL.
When working with a database, we can apply pagination while querying the database itself, so we don't need to fetch every record into our application first.
But the basic idea of pages, limits and selecting the required records remains important.
Watch the Complete Video Tutorial
If you want to see the complete practical implementation, including the frontend and backend code, you can watch the video on our YouTube channel.
Watch: Pagination in Express.js and JavaScript | Coding Blocks

For more practical tutorials on JavaScript, Node.js, Express.js and Full Stack Web Development, explore Coding Blocks.
Keep learning, keep practising and keep building.
Coding Matlab Coding Blocks!