πŸ”₯ All-Access Pass β€” $199 USD (Regular $499) Β· Unlock all 2,836 Astro themes βž”
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Routingβ€’β€’By Komal Nakrani

Astro Pagination: paginate() With Real Examples

Astro pagination with paginate(): build /blog/2/ style pages, paginate tag archives, use the page object for links, and handle on-demand routes by hand.

#Astro#Pagination#Routing#getStaticPaths

Astro pagination works through the paginate() function that Astro passes into getStaticPaths(). You give it an array and a pageSize, return the result, and Astro builds one static page per chunk, passing each page a page prop with the items, the page numbers and ready-made previous and next URLs.

This guide covers the basic route, the page object, tag archives with nested pagination, the [...page] trick for a clean first page, and what to do when your route renders on demand instead of at build time.

Key Takeaways

  • paginate() only exists inside getStaticPaths(), so it is a build-time feature for prerendered routes.
  • Name the file [page].astro or [...page].astro; the param must be called page.
  • page.data holds the items for the current page, and page.url.prev and page.url.next are undefined at the ends.
  • Use [...page].astro when you want page one at /blog/ instead of /blog/1/.
  • For server-rendered routes, read the page number from Astro.params and slice the array yourself.

How Astro pagination works

A paginated route is a dynamic route whose getStaticPaths() returns paginate(items, options). Astro calls it once at build time, splits the array into pages, and creates a route entry for each one. Every generated page receives the same component with a different page prop.

Here is the smallest working version, paginating a blog content collection ten posts at a time:

---
// src/pages/blog/[page].astro
import type { GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';

export const getStaticPaths = (async ({ paginate }) => {
  const posts = (await getCollection('blog', ({ data }) => !data.draft))
    .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

  return paginate(posts, { pageSize: 10 });
}) satisfies GetStaticPaths;

const { page } = Astro.props;
---
<h1>Blog, page {page.currentPage} of {page.lastPage}</h1>

<ul>
  {page.data.map((post) => (
    <li><a href={`/blog/${post.id}/`}>{post.data.title}</a></li>
  ))}
</ul>

<nav aria-label="Pagination">
  {page.url.prev && <a href={page.url.prev} rel="prev">Newer posts</a>}
  {page.url.next && <a href={page.url.next} rel="next">Older posts</a>}
</nav>

With 34 posts this builds /blog/1/, /blog/2/, /blog/3/ and /blog/4/. Sort before you paginate. paginate() keeps the order it receives, and getCollection() makes no promise about order, so an unsorted list gives you pages that shuffle between builds.

If you have not used dynamic routes before, the getStaticPaths guide explains the params and props model that pagination builds on, and the pages and routing docs show where these files live in a theme.

The page prop, field by field

Every paginated page gets a page object of type Page<T>, where T is the item type you passed in. These are the fields Astro sets:

Field Type What it holds
page.data T[] Items on this page
page.start number Index of the first item (zero-based)
page.end number Index of the last item
page.size number Items per page (your pageSize)
page.total number Total items across all pages
page.currentPage number Current page number, starting at 1
page.lastPage number Number of the last page
page.url.current string URL of this page
page.url.prev string | undefined Previous page URL
page.url.next string | undefined Next page URL
page.url.first string | undefined First page URL
page.url.last string | undefined Last page URL

page.start and page.end make β€œShowing 11 to 20 of 34” lines easy: add one to start and end for human numbering. The first and last URLs are undefined when you are already on that page, which suits links you only want to render when they go somewhere.

To type the prop explicitly, import Page and declare Props:

---
// src/pages/blog/[page].astro (typed props)
import type { Page } from 'astro';
import type { CollectionEntry } from 'astro:content';

interface Props {
  page: Page<CollectionEntry<'blog'>>;
}

const { page } = Astro.props;
---

The satisfies GetStaticPaths pattern above infers this for you, so the explicit interface is optional.

Making page one live at /blog/

A plain [page].astro route always produces /blog/1/. Most sites want the first page at /blog/ and the rest at /blog/2/ onward. Rename the file to a rest parameter:

src/pages/blog/[...page].astro

With a rest param, Astro gives the first page an undefined param, which maps to the parent path. The route now produces /blog/, /blog/2/, /blog/3/ and so on, and page.url.prev on page two points at /blog/ automatically. Make sure you do not also have a src/pages/blog/index.astro, or the two routes collide.

Individual posts can still live at src/pages/blog/[slug].astro or src/pages/blog/[...slug].astro. If both the post route and the paginated route are rest params in the same folder, they compete for the same URLs, so give posts a single-segment [slug].astro route or move pagination under a prefix like /blog/page/.

Paginating tag and category archives

Tag archives need one set of pages per tag. Return multiple paginate() calls from the same getStaticPaths() and pass the tag as an extra param:

---
// src/pages/tags/[tag]/[...page].astro
import type { GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';

export const getStaticPaths = (async ({ paginate }) => {
  const posts = (await getCollection('blog'))
    .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

  const tags = [...new Set(posts.flatMap((post) => post.data.tags))];

  return tags.flatMap((tag) =>
    paginate(
      posts.filter((post) => post.data.tags.includes(tag)),
      { params: { tag }, props: { tag }, pageSize: 10 },
    ),
  );
}) satisfies GetStaticPaths;

const { page, tag } = Astro.props;
---
<h1>Posts tagged β€œ{tag}”</h1>
<p>{page.total} posts, page {page.currentPage} of {page.lastPage}</p>

The params option fills the other route segments, and props passes extra data to every page in that set. Tags with special characters need slugging before you use them as params. The full pattern, including tag index pages and URL-safe tag slugs, is in tags and categories pages in Astro.

Previous and next links are enough for a small blog. Once you pass five or six pages, readers want numbered links. Build them from page.currentPage and page.lastPage:

---
// src/components/PageLinks.astro
import type { Page } from 'astro';

interface Props {
  page: Page;
  base: string; // for example '/blog'
}

const { page, base } = Astro.props;
const href = (n: number) => (n === 1 ? `${base}/` : `${base}/${n}/`);
const numbers = Array.from({ length: page.lastPage }, (_, i) => i + 1);
---
<nav aria-label="Pagination">
  <ol>
    {numbers.map((n) => (
      <li>
        {n === page.currentPage
          ? <span aria-current="page">{n}</span>
          : <a href={href(n)}>{n}</a>}
      </li>
    ))}
  </ol>
</nav>

This prints every page, which is fine up to around ten. For longer archives you want a window of pages around the current one with gaps, and that version is in the reusable Astro pagination component, which also handles rel attributes and accessible labels.

Custom URL formats

paginate() accepts a format option, a function that transforms each generated pagination URL before it is set on the page object. It is useful when you deploy to a static file server without clean URLs and need links to end in .html:

// inside getStaticPaths()
return paginate(posts, {
  pageSize: 10,
  format: (url) => `${url}.html`,
});

Astro builds the page.url values with your base and trailingSlash settings applied, so prefer those URLs over strings you assemble yourself. Hand-built links that disagree with the config are the most common source of duplicate URLs on paginated archives; the trailing slash tip covers how to keep config, links and canonicals in agreement.

Pagination on server-rendered routes

getStaticPaths() is ignored on routes that render on demand, and paginate() comes from getStaticPaths(), so there is no built-in pagination helper for server routes. You do it by hand, which is short:

---
// src/pages/search/[...page].astro
export const prerender = false;

import { getCollection } from 'astro:content';

const pageSize = 10;
const current = Number(Astro.params.page ?? 1);
const posts = await getCollection('blog');
const lastPage = Math.max(1, Math.ceil(posts.length / pageSize));

if (!Number.isInteger(current) || current < 1 || current > lastPage) {
  return new Response(null, { status: 404 });
}

const items = posts.slice((current - 1) * pageSize, current * pageSize);
---
<p>Page {current} of {lastPage}</p>

Validate the number before you slice. A server route accepts any string in the URL, so /search/abc/ or /search/9999/ should return a 404 rather than an empty page. Prefer prerendered pagination whenever the data only changes on deploy; it is cheaper and the pages are plain HTML.

SEO for paginated pages

Paginated archives are crawlable lists of links, which helps search engines find older posts. A few rules keep them clean:

  1. Give every page a self-referencing canonical URL. Do not canonicalise page 3 to page 1, because page 3 lists different posts.
  2. Add the page number to the title and description, for example β€œBlog, page 2”, so pages do not share duplicate titles.
  3. Keep rel="prev" and rel="next" on the links. Google no longer uses them as an indexing signal, but they cost nothing and other tools read them.
  4. Link to the first page from your navigation so it collects the most internal links.

The Astro routing docs on pagination and the paginate() API reference are the official sources for every option above.

Blog themes need this pattern on day one. If you would rather start from a site where the blog index, tag archives and pagination already work, the Astro blog and editorial themes ship with them built in.

FAQ

Can I use paginate() in server-rendered Astro pages?

No. paginate() is passed into getStaticPaths(), which only runs for prerendered routes. On a route with export const prerender = false, read the page number from Astro.params, slice your data, and return a 404 for out-of-range numbers.

Why does my first page show at /blog/1/ instead of /blog/?

Your route file is named [page].astro. Rename it to [...page].astro so the first page gets an empty param and renders at the parent path, then remove any index.astro in the same folder to avoid a route conflict.

Does the paginated route param have to be called page?

Yes. paginate() returns params with a page key, so the dynamic segment must be [page] or [...page]. Other segments, such as [tag], are filled through the params option.

How many items per page should an Astro blog use?

Ten to twenty is typical. Fewer items mean more pages to crawl and click through; more items make each page heavier. Pick a number that keeps the archive page fast and fits your card layout, then set it as pageSize.

How do I show the total number of posts on a paginated page?

Use page.total for the count across all pages, and page.start + 1 and page.end + 1 for the range shown on the current page.