Why Server-Side Pagination?
Server-side pagination is particularly beneficial for applications with vast amounts of data that cannot be fully loaded on the client side. By fetching only the required data based on page requests, we reduce load times and optimize resource usage. Next.js 15, with its updated server-side capabilities, allows us to implement robust and SEO-friendly pagination effortlessly.
Step 1: Creating the Data Source for Pagination
We need a source of data to paginate through. This could be a database like MongoDB or a REST API. For simplicity, let’s assume we’re fetching paginated data from a MongoDB collection.
Creat action.js and write this function. /Article.js is Modul of MongoDb and connect.js is function to connect database
"use server";
import Article from "./Acticle";
import connect from "../component/mongo";
export const getPosts=async (page) => {
try {
connect();
const pageSize=3; // that number page showing first page
const pageNumber=page||1// that searchParams or page number
const count=await Article.find({}).countDocuments();
const posts=await Article.find({}).limit(pageSize).skip((pageNumber)*pageSize);
const totalPage=Math.ceil(count/pageSize) // that total of page blogs
return {posts,totalPage};
} catch (err) {
console.log(err);
throw new Error("Failed to fetch posts!");
}
};
Step 2: Building BlogSection component
past this code in page.js
import BlogSection from "./component/BlogSection";
import { getPosts } from "./lib/action";
export default async function Home({ searchParams }) {
const { page } = await searchParams;
const currentPage = parseInt(page);
const data = await getPosts(page);
return (
<div className="">
<BlogSection data={data.posts} totalPages={data.totalPage}
currentPage={currentPage}/>
</div>
)}
Create BlogSection.jsx
import React from "react";
import Card from "./Card";
import ServerPagination from "./Pagination";
const BlogSection = async ({ data, currentPage, totalPages }) => {
return (
<div className="bg-gray-100 md:px-10 px-4 font-[sans-serif]">
<div className="max-w-5xl max-lg:max-w-3xl max-sm:max-w-sm mx-auto">
<div className="flex justify-around items-center mb-8">
<h2 className="text-3xl font-extrabold text-gray-800 mt-4">
Latest Blog Posts</h2>
</div>
<div className="flex flex-wrap">
{data.map((post) => {
return <Card key={post.id} post={post} />
})}
</div>
<ServerPagination totalPages={totalPages}
currentPage={currentPage} />
</div>
</div>
);};
export default BlogSection;
Create Card.jsx component
import React from "react";
import Link from "next/link";
import Image from "next/image";
const Card = ({ post }) => {
return (
<div className="bg-white flex-grow-1">
<Image src={post.image}
alt="Blog Post 1"
className="w-full h-44 object-cover"
width={400}
height={300}
loading="lazy"
quality={80} />
<div className="p-6">
<h3 className="text-lg font-bold text-gray-800 mb-3">
{post.title}
</h3>
<Link href={`/blogs/${post.id}`} className="mt-4 inline-block">
Read More
</Link>
</div>
</div>
)};
export default Card;
Step 2: Building the Pagination Logic in the Server-Side Component
import Link from "next/link";
import React from "react";
const ServerPagination = ({ totalPages, currentPage }) => {
return (
<div
aria-label="Page navigation"
className="flex justify-center flex-wrap mt-16 mb-10">
<Link href={`/?page=${currentPage - 1}`}
className={`${currentPage === 1 ? "hidden": "flex items-center}`}>
Previous
</Link>
{Array.from({ length: totalPages }, (_, index) => (
<div key={index}>
<Link href={`/?page=${index + 1}`}
className={`flex items-center justify-center px-3 h-8 leading-tight border
${currentPage === index + 1 ? "bg-blue-500 text-white": "bg-white text-gray-500"}`}>
{index + 1}
</Link>
</div>
))}
<Link href={`/?page=${currentPage + 1}`}
className={`${totalPages === currentPage? "hidden": "flex items-center" }`}>
Next
</Link>
</div>
);};
export default ServerPagination;
Conclusion
By following these steps, you’ve set up a powerful and SEO-friendly pagination system in Next.js 15, optimized for server-side rendering. Pagination ensures that your application remains efficient and user-friendly while handling large datasets. The server-side approach used here provides pre-rendered, SEO-optimized content, boosting your site's visibility on search engines.