# Next.js

Fetch Mojimoto content in the App Router with @mojimoto/next, cache it, revalidate it on publish and preview drafts with Draft Mode.

`@mojimoto/next` wraps the [JavaScript client](/docs/frameworks/javascript) for the Next.js App Router. It sends requests through Next's `fetch` so they join the Data Cache, switches to drafts when Draft Mode is on, and builds the page the editor uses to preview one section. Pair it with [@mojimoto/react](/docs/frameworks/react) to render what you fetch.

It needs Next.js 14 or newer and works in the App Router only. In the Pages Router, use the JavaScript client directly. This page describes version 0.1.4.

## Install

```bash
npm i @mojimoto/next @mojimoto/react
```

```env .env.local
MOJIMOTO_TOKEN=mjmt_your_read_token
```

## Create the client

```ts lib/cms.ts
import { createMojimotoClient } from '@mojimoto/next'

export const cms = createMojimotoClient({
  endpoint: 'https://mojimoto.com/api/v1',
  project: 'acme',
  token: process.env.MOJIMOTO_TOKEN!,
  revalidate: 60,
  tags: ['cms'],
})
```

`createMojimotoClient` takes every option of [createClient](/docs/frameworks/javascript#create-a-client) and returns the same client, with the same methods. It adds two options, which it passes to every request as Next's `next` fetch option:

| Option | Type | Description |
| --- | --- | --- |
| `revalidate` | `number` or `false` | Seconds before Next fetches a cached response again. `false` keeps it until you revalidate it. |
| `tags` | `string[]` | Cache tags for every request, for `revalidateTag`. |

## Fetch in a Server Component

```tsx app/[uid]/page.tsx
import { notFound } from 'next/navigation'
import { MojiRichText, type MojimotoDocument, type MojiRichTextValue } from '@mojimoto/react'
import { cms } from '@/lib/cms'

type Page = MojimotoDocument<'page', { title: string; body: MojiRichTextValue }>

export default async function PageRoute({ params }: { params: Promise<{ uid: string }> }) {
  const { uid } = await params

  const page = await cms.byUid<Page>('page', uid)

  if (!page) {
    notFound()
  }

  return (
    <main>
      <h1>{page.data.title}</h1>
      <MojiRichText field={page.data.body} linkResolver={(link) => `/${link.uid}`} />
    </main>
  )
}
```

On Next.js 14, `params` is a plain object, not a promise.

## Revalidate on publish

With `revalidate: 60`, Next fetches content again at most once a minute. To refresh it when an editor publishes, add a route that clears the tag and point a [webhook](/docs/concepts/webhooks) at it.

```ts app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache'
import { verifyWebhookSignature } from '@mojimoto/client'

export async function POST(request: Request) {
  const signed = await verifyWebhookSignature({
    body: await request.text(),
    signature: request.headers.get('x-mojimoto-signature'),
    secret: process.env.MOJIMOTO_WEBHOOK_SECRET!,
  })

  if (!signed) {
    return new Response('Bad signature', { status: 401 })
  }

  revalidateTag('cms', 'max')

  return Response.json({ revalidated: true })
}
```

- `verifyWebhookSignature` comes from `@mojimoto/client`. Add it to your own dependencies with `npm i @mojimoto/client`.
- Next.js 16 wants the second argument to `revalidateTag`. On 14 and 15, call `revalidateTag('cms')`.
- Subscribe the webhook to `document.published`, `document.unpublished` and `document.deleted`.

> **Note:** Keep `revalidate` as a number even with the webhook. Published responses are sent with `s-maxage=60`, so a shared cache between your site and the API can answer a fetch made the moment after a publish with the older copy. See [HTTP details](/docs/api/http-details).

## Preview drafts with Draft Mode

`createDraftAwareClient` makes a client that follows Next's Draft Mode. When Draft Mode is on it asks for drafts and sets `revalidate` to `0`. Otherwise it behaves like `createMojimotoClient`.

```ts lib/cms.ts
import { createDraftAwareClient } from '@mojimoto/next'

export function getCms() {
  return createDraftAwareClient({
    endpoint: 'https://mojimoto.com/api/v1',
    project: 'acme',
    token: process.env.MOJIMOTO_TOKEN!,
    revalidate: 60,
    tags: ['cms'],
  })
}
```

It is async and reads the request, so call it inside a Server Component or a route handler, not at the top of a module: `const cms = await getCms()`. The token needs the `preview` ability. Without it the API returns published content and no error.

Two route handlers turn Draft Mode on and off:

```ts app/api/preview/route.ts
import { createPreviewHandler } from '@mojimoto/next/preview'

export const GET = createPreviewHandler({
  secret: process.env.MOJIMOTO_PREVIEW_SECRET!,
  defaultRedirect: '/',
})
```

```ts app/api/preview/exit/route.ts
import { createExitPreviewHandler } from '@mojimoto/next/preview'

export const GET = createExitPreviewHandler({ defaultRedirect: '/' })
```

Open `/api/preview?secret=your-secret&redirect=/about` to turn Draft Mode on and land on `/about`. A wrong `secret` gets a 401. `redirect` has to be a path on your own site. Anything else is replaced by `defaultRedirect`, which is `/` unless you set it. `/api/preview/exit` turns Draft Mode off and takes `redirect` too.

To open that URL from the editor, set the project's **Preview base URL** to your site and the content type's **Preview path** to something like `/api/preview?secret=your-secret&redirect=/{uid}`. See [Preview](/docs/concepts/preview).

## Preview one section

`createSlicePreviewPage` builds a page that fetches one entry by content type and UID and renders it through your section components. It is the URL the editor opens and screenshots for a section.

```tsx app/preview/[type]/[uid]/page.tsx
import { createSlicePreviewPage } from '@mojimoto/next/preview'
import { cms } from '@/lib/cms'
import { components } from '@/cms/sections'

export default createSlicePreviewPage({ client: cms, components })
```

Set the content type's **Preview path** to `/preview/{type}/{uid}`. `npx @mojimoto/cli add-preview` writes this file and a starting `components` map for you. See the [CLI](/docs/tools/cli).

| Option | Type | Description |
| --- | --- | --- |
| `components` | `SliceComponents` | A component for each content type, the same map [SliceZone](/docs/frameworks/react#render-blocks-and-sections) takes. |
| `client` | a client, or a function returning one | Used to fetch the entry. |
| `preview` | `boolean` | Fetch the draft. Off by default, whatever the client's own `preview` option says. |
| `lang` | `string` | The locale when the URL has no `?lang=`. |
| `context` | anything | Passed to every component as `context`. |
| `wrapper` | component | Wraps the section, for global styles or fonts. |

An entry that does not exist gets Next's 404 page.

> **Warning:** This route is public. With `preview: true` it shows drafts to anyone who has the URL. Give it a client created with `revalidate: 0` as well, or Next caches a draft like any other response.

## Use next/image

Asset URLs are plain file URLs, so let `next/image` do the resizing. Allow the asset host first. Today assets are served from a host matching `*.laravel.cloud`.

```js next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [{ protocol: 'https', hostname: '*.laravel.cloud' }],
  },
}

export default nextConfig
```

A `media` field arrives with its size, which is what `next/image` needs:

```tsx components/CoverImage.tsx
import Image from 'next/image'

type Media = { url: string; alt: string | null; width: number | null; height: number | null }

export function CoverImage({ image }: { image: Media | null }) {
  if (!image?.width || !image.height) {
    return null
  }

  return <Image src={image.url} alt={image.alt ?? ''} width={image.width} height={image.height} />
}
```

`width` and `height` can be `null`, for example on content that was imported as a bare URL. Handle that case with `fill` or a plain `img`. If Next refuses an image, compare the `url` of one of your assets with the pattern above.

## Everything the package exports

| Import from | Exports |
| --- | --- |
| `@mojimoto/next` | `createMojimotoClient`, `createDraftAwareClient`, `MojimotoError`, and the types `NextClientOptions` and `MojimotoClient`. |
| `@mojimoto/next/preview` | `createPreviewHandler`, `createExitPreviewHandler`, `createSlicePreviewPage`, `safeRedirect`, and the types `PreviewHandlerOptions`, `SlicePreviewPageOptions` and `SlicePreviewPageProps`. |

`safeRedirect(target, defaultRedirect)` is the check the handlers use. It returns `target` if it is a path on the same site, otherwise `defaultRedirect`, otherwise `/`.
