#How to have pagination on a `[slug].astro` route?

4 messages · Page 1 of 1 (latest)

upbeat ocean
#

My use-case is to have a page containing all posts from an author with pagination. So if you access /blog/author/author-name it will list all pages from the author-name with pagination.

pearl meadowBOT
#

Hi @upbeat ocean. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can’t paginate directly on a [slug].astro file name, because Astro’s built‑in paginate() assumes a [page].astro or [...page].astro param for the page number. [paginate ref]

To support URLs like /blog/author/author-name and pagination, you need a dynamic route that includes both the author slug and the page number, e.g.:

  • /blog/author/[author]/[page].astro/blog/author/author-name/1, /blog/author/author-name/2, …

This is the same pattern Astro calls “nested pagination”. [Nested pagination]

1. Create a nested paginated route

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

---
export async function getStaticPaths({ paginate }) {
  // 1. Load all posts (from your CMS, content collection, etc.)
  const allPosts = /* fetch or getCollection() here */ [];

  // 2. Get all unique authors
  const allAuthors = Array.from(new Set(allPosts.map((post) => post.authorSlug)));

  // 3. For each author, filter posts and call paginate()
  return allAuthors.flatMap((author) => {
    const authorPosts = allPosts.filter((post) => post.authorSlug === author);

    return paginate(authorPosts, {
      pageSize: 10,
      params: { author }, // important: pass the author param
    });
  });
}

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

<h1>Posts by {author}</h1>

<ul>
  {page.data.map((post) => (
    <li>{post.title}</li>
  ))}
</ul>

{page.url.first ? <a href={page.url.first}>First</a> : null}
{page.url.prev ? <a href={page.url.prev}>Previous</a> : null}
{page.url.next ? <a href={page.url.next}>Next</a> : null}
{page.url.last ? <a href={page.url.last}>Last</a> : null}
#

This follows the same pattern as the docs’ nested pagination example, just grouping by author instead of tag. [Nested pagination]

2. Make /blog/author/author-name hit page 1

If you specifically need /blog/author/author-name (without /1), you’d use a rest parameter instead:

src/pages/blog/author/[...page].astro and interpret the first segment as the author and the optional second segment as the page number. However, the knowledge sources don’t show an official pattern combining paginate() with a rest parameter like this, so I can’t provide a documented example for that case.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: