# Next.js kit

> Build a Next.js 16 site on Galerne with @galerne/next. Queries are cached and tagged with what they read, publishing purges exactly those pages, and editors preview drafts next to the editor.

`@galerne/next` connects a Next.js 16 site to a Galerne project. It gives you:

- `query()` and `getDoc()` cached with `"use cache"` and tagged with the documents each answer read, so a publish refreshes only the pages that show the change
- draft previews on any content branch, read fresh with a token that stays on the server
- the live preview in the studio: the site next to the editor, refreshed after each save, where a click on the page focuses the field
- route handlers for preview, revalidation and `llms.txt`, plus sitemap and robots helpers
- `<RichText>`, `<Image>` and `<Blocks>` components, and routing for sites in several languages

The Next.js starter in the Galerne repository (`examples/nextjs`) is a complete site built on it.

## Install

```bash
npm i @galerne/next @galerne/client
```

Turn on Cache Components in `next.config.ts`:

```ts
const nextConfig = { cacheComponents: true, partialPrefetching: true }
export default nextConfig
```

Set the environment:

| Variable | What it holds |
|---|---|
| `GALERNE_API_URL` | `https://api.galerne.cloud` |
| `GALERNE_PROJECT` | The project slug |
| `GALERNE_PREVIEW_TOKEN` | A token with the `read` scope, for drafts |
| `GALERNE_PREVIEW_SECRET` | The preview secret from **Settings**, **General**, **Preview** |
| `GALERNE_WEBHOOK_SECRET` | The secret of the revalidation webhook |
| `GALERNE_STUDIO_URL` | The studio that frames the preview |
| `SITE_URL` | The public URL of the site |

## Create the kit

```ts
// lib/galerne.ts
import type { DocsOf } from '@galerne/client'
import { createGalerne } from '@galerne/next'
import config from '@/galerne.config'

export type Docs = DocsOf<typeof config, { format: 'json'; lang: true; expand: true }>

export const galerne = createGalerne<Docs>({
  project: process.env.GALERNE_PROJECT!,
  apiUrl: process.env.GALERNE_API_URL!,
  previewToken: process.env.GALERNE_PREVIEW_TOKEN,
  previewSecret: process.env.GALERNE_PREVIEW_SECRET,
  webhookSecret: process.env.GALERNE_WEBHOOK_SECRET,
  studioUrl: process.env.GALERNE_STUDIO_URL,
  siteUrl: process.env.SITE_URL,
  languages: ['en', 'fr'],
  defaultLanguage: 'en',
  routes: { post: '/{lang}/blog/{slug}', page: '/{lang}/{slug}' },
})
```

`expand: true` types references as either `{ _ref }` or the whole referenced document. When queries expand with chosen fields, give the same map instead, and a reference to a project becomes `{ _id, _type: 'project', _lang?, title, slug?, cover? } | null`:

```ts
export type Docs = DocsOf<typeof config, { format: 'json'; lang: true; expand: { project: ['title', 'slug', 'cover']; '*': ['title', 'slug'] } }>

const { items } = await galerne.query({ type: 'page', expand: { project: ['title', 'slug', 'cover'], '*': ['title', 'slug'] } })
```

See [references](/docs/query.md#references) for what the API returns.

`routes` uses the same patterns as the routes in [site settings](/docs/site.md). Set them in both places: the kit builds links with them, the studio finds the page of each document with them.

## Mount the routes

```ts
// app/api/galerne/preview/route.ts
import { galerne } from '@/lib/galerne'
export const { GET } = galerne.handlers.preview
```

| File | Export |
|---|---|
| `app/api/galerne/preview/route.ts` | `export const { GET } = galerne.handlers.preview` |
| `app/api/galerne/exit/route.ts` | `export const { GET, POST } = galerne.handlers.exit` |
| `app/api/galerne/revalidate/route.ts` | `export const { POST } = galerne.handlers.revalidate` |
| `app/llms.txt/route.ts` | `export const { GET } = galerne.handlers.llms` |
| `app/sitemap.ts` | `return galerne.sitemap()` |
| `app/robots.ts` | `return galerne.robots()` |

## Read content

```tsx
// app/[lang]/blog/[slug]/page.tsx
import { notFound, redirect } from 'next/navigation'
import { galerne } from '@/lib/galerne'

export default async function Post({ params }: PageProps<'/[lang]/blog/[slug]'>) {
  const { lang, slug } = await params
  const { doc: post, redirect: moved } = await galerne.bySlug('post', slug, lang)
  if (moved) redirect(moved)
  if (!post) notFound()
  const edit = await galerne.editable()
  return (
    <article>
      <h1 {...edit(post, 'title')}>{post.title}</h1>
      <galerne.Image image={post.cover} sizes="(min-width: 60rem) 56rem, 100vw" priority />
      <galerne.RichText value={post.body} lang={lang} />
    </article>
  )
}
```

`galerne.query(q)` takes the [query API](/docs/query.md) input, typed from your schema, and returns rich text as ProseMirror JSON unless you set `format`. In `generateStaticParams` and feeds, pass `{ published: true }` as the second argument: they run outside a request.

## Caching and revalidation

Every query answer lists the cache tags it depends on: `type:<type>` when it lists a type, `doc:<id>` for each document in it, expanded references included. The kit stores the answer with `"use cache"`, `cacheLife('max')` and one `cacheTag` per tag, prefixed with the project (`gal:<project>:doc:<id>`).

Webhook events carry the tags they change. Add a [webhook](/docs/webhooks.md) to `https://<site>/api/galerne/revalidate` for `doc.published`, `doc.unpublished`, `doc.deleted`, `branch.promoted`, `release.published`, `release.rolled_back` and `schema.deployed`. The route checks the signature and calls `revalidateTag` for each tag:

| Event | What is purged |
|---|---|
| Publish, unpublish or delete on `main` | The document, the lists of its type, and queries with no type |
| Promotion or release that publishes | Every document it changed |
| Schema deploy, rollback | The whole project |
| Edits to drafts, other branches | Nothing |

Change the lifetime with `cacheLife` (a profile name or `{ stale, revalidate, expire }`), and how long purged pages may still be served while they refresh with `staleAfterPurge` (seconds, `0` by default).

### Cache settings per type

Most projects keep the defaults. When a type needs more, an admin sets it in the studio (settings, cache) or with the `set_cache_settings` tool:

- `life`: how long answers about this type stay cached (`seconds`, `minutes`, `hours`, `days`, `weeks` or `max`). Query answers carry it as `cacheLife`, and the kit uses it. When an answer covers several types, the shortest lifetime applies. A `cacheLife` given to a single read still wins.
- `purges`: other types that a change of this type also refreshes. With `post: { purges: ['page'] }`, publishing a post purges `type:page` too, for example a home page that lists the latest posts.

```json
{ "types": { "event": { "life": "hours" }, "post": { "purges": ["page"] } } }
```

## Live preview

1. In the studio, **Settings**, **General**: set the routes and the **preview URL**, the origin of the site (`https://preview.example.com`). Galerne makes a preview secret; set it as `GALERNE_PREVIEW_SECRET` on the site.
2. Render `<galerne.LivePreview />` once in the root layout. Outside preview it renders nothing.
3. Open a document and press **preview**.

The studio frames `<preview URL>/api/galerne/preview?secret=…&branch=…&redirect=<page>`. The route turns on draft mode, keeps the branch in a cookie and opens the page. Pages then read drafts on that branch, uncached. After each save the studio asks the page to refresh. A click on an element marked with `edit()` focuses that field in the editor; alt+click does it on links too. Messages go both ways only between the studio and the preview origin.

The site must accept being framed by the studio: no `X-Frame-Options: DENY`, and with a CSP, `frame-ancestors 'self' https://studio.galerne.cloud`. In production, preview needs HTTPS: the draft mode cookie is `SameSite=None; Secure`. Browsers that block cookies in frames, like Safari, show the published page in the pane; the preview link still works in a new tab.

See [visual editing](/docs/visual-editing.md) for the attribute format.

## Components

| Component | What it renders |
|---|---|
| `galerne.Image` | `srcset` from media transforms up to the original width, `width` and `height`, the hotspot as `object-position`, the alt text. `ratio` crops, `format` picks the output (WebP by default). |
| `galerne.RichText` | ProseMirror JSON as HTML elements. `doc:` links become page paths in the reader's language, `media:` images get a `srcset`, unsafe links are dropped, embedded blocks render through `blocks`. |
| `Blocks` | A blocks field through a registry: block type → component. Each component gets `{ block, index, edit, props }`. |
| `galerne.EditTarget` | Any element marked as one field, for click to edit. |
| `galerne.LivePreview` | In preview only: the overlay and the bridge to the studio. |

```tsx
import { Blocks, type BlockProps, type BlockRegistry } from '@galerne/next'

function Hero({ block, edit }: BlockProps<HeroBlock>) {
  return <h2 {...edit('heading')}>{block.heading}</h2>
}

export const blocks: BlockRegistry<PageBlock> = { hero: Hero, quote: Quote }

// A blocks field, with click to edit:
<Blocks value={page.blocks} components={blocks} doc={page} field="blocks" edit={await galerne.editable()} />

// Blocks embedded in rich text use the same registry:
<galerne.RichText value={post.body} lang={lang} blocks={blocks} />
```

## Languages

The kit follows one model: one document per language, linked by `_translationOf` (see [schema](/docs/schema.md)).

```ts
// proxy.ts
import { createI18nProxy } from '@galerne/next/proxy'

export const proxy = createI18nProxy({ languages: ['en', 'fr'], defaultLanguage: 'en' })
export const config = { matcher: ['/((?!api/|_next/|sitemap.xml|robots.txt|llms.txt|.*\\.[a-z0-9]+$).*)'] }
```

| Helper | What it does |
|---|---|
| `createI18nProxy` | Sends `/` to the reader's language from `Accept-Language`, and paths without a language to the default one. With `prefixDefault: false` the default language lives at the root. |
| `galerne.bySlug(type, slug, lang)` | The document in that language, the default language as fallback, or a redirect when the slug belongs to another language. |
| `galerne.translations(doc)` | The path of the document in each language. |
| `galerne.alternates(doc, lang)` | `canonical` and hreflang links, with `x-default`, for `generateMetadata`. |
| `galerne.languageSwitcher(doc, lang)` | Links for a language menu: the translation, or that language's home page. |
| `galerne.strings(lang)` | UI strings from a `strings` singleton, so editors and agents translate them in the studio. |
