# Fetching Published Content

> How websites, mobile apps, and static site generators query published content from the Delivery API—including filtering, reference expansion, derived reading stats, and draft previews.

Your public website, mobile app, or static site generator (Next.js, Astro, Remix, Nuxt, SvelteKit, etc.) fetches published content from the **Delivery API** (`/delivery/v1/*`).

The Delivery API is **strictly read-only** and only returns **published** content—drafts, AI instructions, user records, and internal admin settings are never exposed.

---

## Core Delivery Endpoints

| Goal | Endpoint |
| :--- | :--- |
| Site info & locales | `GET /delivery/v1/site` |
| List entries in a collection | `GET /delivery/v1/{postType}` |
| Fetch one entry by slug or ID | `GET /delivery/v1/{postType}/{idOrSlug}` |
| Fetch a singleton (e.g. Homepage) | `GET /delivery/v1/singletons/{slug}` |
| Fetch all automatic 301 redirects | `GET /delivery/v1/redirects` |
| Fetch sitemap entries | `GET /delivery/v1/sitemap.json` |
| Stream a media file | `GET /delivery/v1/media/{id}` |

<Note>
  By default, the Delivery API is public (no key required). If you want to restrict Delivery reads to your own client server, set `OVERTCMS_DELIVERY_REQUIRE_API_KEY=true` and pass `Authorization: Bearer <your-client-key>` using a `public_read` key from **API Keys** in Admin.
</Note>

---

## Common Client Recipes

### 1. Fetch a Paginated List of Posts

```ts
const res = await fetch(
  "https://cms.example.com/delivery/v1/posts?sort=-publishedAt&limit=10&expand=author,category&include=wordCount,readingTime"
);
const { items, nextCursor, hasMore } = await res.json();
```

Use `nextCursor` on the next request (`?cursor=<nextCursor>`) to load the next page—OvertCMS uses fast keyset pagination instead of slow offset paging.

### 2. Fetch a Single Post with Expanded References & Table of Contents

Without `expand`, reference fields return only the linked entry's ID. Passing `?expand=author,category` hydrates those references inline in a single request (no N+1 waterfalls!).

```ts
const res = await fetch(
  "https://cms.example.com/delivery/v1/posts/hello-overtcms?expand=author,category&depth=1&include=headings,wordCount,readingTime"
);
const { entry } = await res.json();
```

### 3. Filter & Select Only the Fields You Need

```http
GET /delivery/v1/posts?filter[featured][eq]=true&fields=title,slug,excerpt,publishedAt&sort=-publishedAt
```

- Only fields marked **Filterable** in your Content Model can be filtered (`eq`, `in`, `contains`, `gte`, `lte`).
- System fields (`locale`, `slug`, `publishedAt`, `createdAt`, `updatedAt`) are always filterable and sortable.

### 4. Fetch Hierarchical Pages as a Nested Tree

For documentation or nested page collections (any collection with a self-referencing `parent` field), pass `?tree=true` to receive nested `children[]` arrays ready for a sidebar:

```http
GET /delivery/v1/docs?tree=true&fields=title,slug
```

### 5. Preview an Unpublished Draft

When your site has a **Public Website URL** configured in **Site Settings** and your Content Model has a **URL Pattern** (for example `/blog/{slug}`), clicking **Preview** in Admin automatically mints a short-lived, single-entry preview token (`pv_...`) and opens your live client page with a `?preview=<token>` query parameter:

```text
https://yoursite.com/blog/my-draft-post?preview=pv_abc123...
```

In your client route (Next.js App Router, Astro, Remix, SvelteKit, Nuxt, etc.), read the `preview` query parameter and forward it to OvertCMS Delivery in the `X-Preview-Token` header:

```ts
// Example: Next.js App Router page (app/blog/[slug]/page.tsx)
export default async function BlogPostPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ preview?: string }>;
}) {
  const { slug } = await params;
  const { preview: previewToken } = await searchParams;

  const res = await fetch(
    `https://cms.example.com/delivery/v1/posts/${encodeURIComponent(slug)}`,
    {
      headers: previewToken ? { "X-Preview-Token": previewToken } : undefined,
      cache: previewToken ? "no-store" : "force-cache",
    }
  );

  if (!res.ok) notFound();
  const { entry, preview } = await res.json();

  return (
    <article>
      {preview && <div className="preview-banner">Draft preview</div>}
      <h1>{entry.data.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: entry.data.body }} />
    </article>
  );
}
```

For singletons (such as a Homepage), use the same pattern against `GET /delivery/v1/singletons/{slug}` with the `X-Preview-Token` header.

<Note>
  **Security & caching guarantees:** Core binds each `pv_...` token strictly to a single entry and expires it automatically (default 30 minutes, max 24 hours). Core requires the token in the `X-Preview-Token` request header (not the Delivery query string), bypasses the L2 cache, and returns `Cache-Control: private, no-store` with no `Surrogate-Key` so unpublished drafts never leak to live visitors or CDNs. Consider adding `<meta name="robots" content="noindex" />` on your client whenever `preview === true`.
</Note>

---

## Query Parameters at a Glance

| Parameter | Example | What It Does |
| :--- | :--- | :--- |
| `locale` | `?locale=fr` | Fetch content for a specific site locale. |
| `expand` | `?expand=author,category` | Inline-hydrate top-level `reference` fields. |
| `depth` | `?depth=2` | Nesting depth when `expand` is used (`1` default, `2` max). |
| `include` | `?include=plainText,wordCount,readingTime,headings` | Compute derived projections for `rich_html` fields. |
| `fields` | `?fields=title,slug,body` | Return only the listed `data` keys to shrink payload size. |
| `filter[f][op]` | `?filter[category][eq]=guides` | Filter on filterable or system fields (`eq`, `in`, `contains`, `gte`, `lte`). |
| `sort` | `?sort=-publishedAt` | Sort ascending (`title`) or descending (`-publishedAt`). |
| `limit` / `cursor` | `?limit=20&cursor=...` | Keyset pagination (`limit` max `100`). |
| `parent` / `tree` | `?parent=root` or `?tree=true` | Query hierarchical self-referencing collections. |

---

## Caching Headers Built In

Every public Delivery response includes production caching headers out of the box:

- **`ETag`**: Send `If-None-Match` on repeat requests to get `304 Not Modified`.
- **`Cache-Control`**: `public, max-age=60, stale-while-revalidate=300` (or `private, max-age=60` when Delivery API key auth is required).
- **`Surrogate-Key`**: Space-delimited cache tags (`site:default type:posts entry:<id>`) for instant CDN purges.
- **`X-OvertCMS-Cache`**: Shows `HIT` or `MISS` from Core's built-in L2 cache (in-memory LRU or Redis/Valkey).

<Tip>
  **Test live in Admin:** Open **Webhooks & Logs → API Explorer** in the Admin UI to build Delivery URLs visually, test `expand`, `include`, `sort`, and `tree=true`, inspect live cache headers, and copy ready-to-run `curl` commands.
</Tip>
