# Pagination

> Split a blog or another index page into numbered pages. Works with the Next.js SDK, the client package, static builds, and the JSON API.

Source: https://docs.rootsmith.io/publishing/pagination.md

An index page, such as `/blog`, lists the published pages of one page type.
When the list gets long, split it into numbered pages: `/blog` shows the
newest posts, `/blog/page/2` shows the next ones, and so on.

Put the page number in the path, not in a `?page=` query string. A static
host can't read a query string, and each numbered page gets its own URL in
search results.

## Read one page of the list

`listPages` returns one page of the list and the number of posts that match:

```ts
const { pages, total } = await rootSmith.listPages({
  prefix: "/blog",
  sort: "newest",
  page: 2,
  limit: 10,
})
```

| Option   | Description                                                                                                |
| -------- | ---------------------------------------------------------------------------------------------------------- |
| `prefix` | A page type's URL prefix, such as `/blog`. Returns only pages under it. `/blog` and `/blog/` are the same. |
| `sort`   | `"path"`, the default, or `"newest"`, which sorts by `publishedAt` with the newest first.                  |
| `page`   | The page number. It starts at 1.                                                                           |
| `limit`  | Posts on each page, from 1 to 100. The default is 25.                                                      |

`total` counts every post under `prefix`, on all pages. The number of pages
is `Math.ceil(total / limit)`.

`listAllPages({ prefix, sort })` takes the same `prefix` and `sort` and
returns every post that matches.

Page type prefixes are in **Sites** → **Page types**, or in `get_site` for an
agent.

## Next.js

These three files work with a server and with `output: "export"`. Keep your
catch-all route for the posts. Next.js matches `app/blog/page/[n]` first.

```tsx title="app/blog/post-list.tsx"
import Link from "next/link"
import { notFound } from "next/navigation"
import { rootSmith } from "@/lib/rootsmith"

export const perPage = 10

export async function PostList({ page }: { page: number }) {
  const { pages: posts, total } = await rootSmith.listPages({
    prefix: "/blog",
    sort: "newest",
    page,
    limit: perPage,
  })
  if (page > 1 && !posts.length) notFound()
  const pageCount = Math.ceil(total / perPage)
  return (
    <>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <Link href={post.path}>{post.title}</Link>
            <p>{post.description}</p>
          </li>
        ))}
      </ul>
      <nav>
        {page > 1 && (
          <Link href={page === 2 ? "/blog" : `/blog/page/${page - 1}`}>
            Newer posts
          </Link>
        )}
        {page < pageCount && (
          <Link href={`/blog/page/${page + 1}`}>Older posts</Link>
        )}
      </nav>
    </>
  )
}
```

```tsx title="app/blog/page.tsx"
import { PostList } from "./post-list"

export default function BlogIndex() {
  return <PostList page={1} />
}
```

```tsx title="app/blog/page/[n]/page.tsx"
import { notFound } from "next/navigation"
import { rootSmith } from "@/lib/rootsmith"
import { PostList, perPage } from "../../post-list"

type Props = { params: Promise<{ n: string }> }

export async function generateStaticParams() {
  const { total } = await rootSmith.listPages({ prefix: "/blog", limit: 1 })
  const pageCount = Math.max(Math.ceil(total / perPage), 1)
  return Array.from({ length: pageCount }, (_, index) => ({
    n: String(index + 1),
  }))
}

export default async function BlogPage({ params }: Props) {
  const page = Number((await params).n)
  if (!Number.isInteger(page) || page < 2) notFound()
  return <PostList page={page} />
}
```

- `/blog` is page 1, so `/blog/page/1` renders as a 404. It also keeps a
  static export building when there is only one page, because Next.js
  rejects an empty `generateStaticParams` under `output: "export"`.
- With a server, a page number after the last page returns a 404. The pages
  refresh when you publish, like page reads.
- With a static export, each publish starts a new build, which makes the
  new set of pages.

## Other JavaScript servers

In Astro, SvelteKit, Nuxt, and other servers, read one page of the list on
each request:

```ts title="lib/blog.ts"
import { rootSmith } from "./rootsmith"

export const perPage = 10

export async function postPage(page: number) {
  const { pages, total } = await rootSmith.listPages({
    prefix: "/blog",
    sort: "newest",
    page,
    limit: perPage,
  })
  return { posts: pages, pageCount: Math.ceil(total / perPage) }
}
```

Call `postPage(1)` in the route for `/blog`. Add a route for
`/blog/page/[n]` that sends a 404 when `n` isn't a whole number of 2 or
more, or when there are no posts. For example, in SvelteKit:

```ts title="src/routes/blog/page/[n]/+page.server.ts"
import { error } from "@sveltejs/kit"
import { postPage } from "$lib/blog"
import type { PageServerLoad } from "./$types"

export const load: PageServerLoad = async ({ params }) => {
  const page = Number(params.n)
  if (!Number.isInteger(page) || page < 2) error(404)
  const result = await postPage(page)
  if (!result.posts.length) error(404)
  return { ...result, page }
}
```

If you cache pages, the [refresh callback](https://docs.rootsmith.io/publishing/frameworks.md#caching)
gets the path of the post that changed, not of the index. Clear your cached
index pages too, such as every cached path that starts with `/blog`.

## Static builds

A static build reads every post anyway. Read the list once with `prefix`
and `sort`, then split it with your generator's paginator. For example,
Astro's `paginate` builds `/blog`, `/blog/2`, `/blog/3`, and so on:

```astro title="src/pages/blog/[...page].astro"
---
import type { GetStaticPaths } from "astro"
import { createRootSmith } from "@rootsmithio/client"

export const getStaticPaths = (async ({ paginate }) => {
  const rootSmith = createRootSmith({
    siteId: import.meta.env.ROOTSMITH_SITE_ID,
  })
  const posts = await rootSmith.listAllPages({
    prefix: "/blog",
    sort: "newest",
  })
  return paginate(posts, { pageSize: 10 })
}) satisfies GetStaticPaths

const { page } = Astro.props
---

<ul>
  {page.data.map((post) => (
    <li><a href={post.path}>{post.title}</a></li>
  ))}
</ul>
{page.url.prev && <a href={page.url.prev}>Newer posts</a>}
{page.url.next && <a href={page.url.next}>Older posts</a>}
```

For a Next.js static export, use the [Next.js](#nextjs) files above.

Hugo and Jekyll read posts into your content folder, as the
[static sites](https://docs.rootsmith.io/publishing/static-sites.md) guide shows. Then their own
paginators work, such as Hugo's `.Paginate` or a Jekyll pagination plugin.

## JSON API

The public JSON API takes the same options as query parameters. The
`X-Total-Count` response header has the total:

```bash
curl -i "https://api.rootsmith.io/v1/delivery/$ROOTSMITH_SITE_ID/pages?prefix=/blog&sort=newest&page=2&limit=10"
```

The response body is an array of pages. A request with no options returns
up to 25 pages, sorted by path.

## WordPress and MDX export

WordPress makes its own post lists and pages. With
[MDX export](https://docs.rootsmith.io/publishing/mdx-export.md), use your site's own pagination.
