Adding pagination in Node/Express blog site

Hey guys, I’m building a blog site and trying to use pagination to display different pages of blog posts when there are more than 3 posts stored in the database. I’m trying to pass data from the front-end when pushing “newer” or “previous” buttons to the back-end to control the direction of the pages. How can I go about doing that?

What I want to do is pass data from the front-end buttons up top to the route below so that the currentPage variable will increment or decrement. From there, it will render the appropriate posts depending on which direction the user clicks. I tried testing it by manipulating the currentPage variable manually and it works. I just need help on how to control that from the buttons on the front-end. I hope I’m making sense.

Any help would be greatly appreciated.

This is the code in the front-end that controls the “next” and “previous” buttons.

<% if(totalItems > 3){ %>
  <div class="page-buttons">
    <form action="/">   
      <button type="submit" class="btn btn-outline-info newer-posts">Next</button>

    <button type="submit" class="btn btn-outline-info older-posts">Previous</button>
    </form>
    
  </div>
  <% } %>

Here is the route that handles displaying the posts.

app.get("/", (req, res) => {
  let currentPage = 1;
  let perPage = 3;
  let totalItems;

  Post.find()
    .countDocuments()
    .then(count => {
      totalItems = count;
      Post.find()
        .skip((currentPage - 1) * perPage)
        .limit(perPage)
        .then(posts => {
          res.render("home", {
            posts: posts,
            totalItems: totalItems,
            currentPage: currentPage
          });
        });
    })
});

I’m not sure if i understand correctly but looks like you’re almost there^^
Just let the next/previous button to send down currentpage +/-1^^ ( in a query param )

Oh, of course you do not want to display previous button on page 1 as well as next button on the last one ^^ Disable them or make them appear conditionally^^