> For the complete Lynkow documentation index in agent-friendly format, see [llms.txt](/llms.txt).

# Draft Preview

**Publié le** : 2026-11-30
**Catégorie** : Advanced

> **Reference** - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
> 
> - SDK: [`ContentsService`](/sdk/services/sdk-contents-service)
> - API: [Admin API](/admin-api/api-overview)

## Prerequisites

- A shared client in `@/lib/lynkow` ([Add Lynkow to an Existing Project](/sdk/getting-started/existing-project))
- A Next.js App Router project
- An API token with the `contents.view` permission, created in the dashboard under **Settings > Developers > API**

## How It Works

The SDK reads the storefront API, which serves published content only. Unpublished content comes from `GET /v1/contents/slug/:slug`, which takes your secret API token and returns content in any status. Your site turns on Next.js Draft Mode from a route protected by a secret, and the article page reads from `/v1` while Draft Mode is on.

The dashboard does not link to this route. Editors open its URL themselves, for example `https://yoursite.com/api/preview?secret=...&slug=my-article`.

Add two server-only variables next to the ones from the client setup:

```bash
# .env.local
LYNKOW_PREVIEW_SECRET=   # a random string, for example from: openssl rand -hex 32
LYNKOW_API_TOKEN=lkw_sk_...
```

Neither takes the `NEXT_PUBLIC_` prefix: the token reads every content of the site, drafts included.

## Fetch a Draft

```typescript
// lib/draft.ts
import type { TipTapNode } from 'lynkow'

export async function fetchDraft(slug: string) {
  const response = await fetch(
    `https://api.lynkow.com/v1/contents/slug/${encodeURIComponent(slug)}`,
    {
      headers: {
        Authorization: `Bearer ${process.env.LYNKOW_API_TOKEN}`,
        'X-Site-Id': process.env.NEXT_PUBLIC_LYNKOW_SITE_ID!, // needed by an organization token
      },
      cache: 'no-store',
    }
  )
  if (response.status === 404) return null
  if (!response.ok) throw new Error(`Lynkow /v1 answered ${response.status}`)

  const { data } = await response.json()
  return data as { id: string; title: string; status: string; body: TipTapNode }
}
```

The `/v1` response differs from the SDK's `Content` in two ways:

- `body` is the editor document as JSON (a `TipTapNode` tree), with variable placeholders not replaced. It is not HTML: render it with a renderer of your own.
- The slug is matched without a locale. When translations share a slug, read `GET /v1/contents/:id` instead.

## Turn Preview On and Off

```typescript
// app/api/preview/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
import type { NextRequest } from 'next/server'
import { fetchDraft } from '@/lib/draft'

export async function GET(request: NextRequest) {
  const secret = request.nextUrl.searchParams.get('secret')
  const slug = request.nextUrl.searchParams.get('slug')

  if (!process.env.LYNKOW_PREVIEW_SECRET || secret !== process.env.LYNKOW_PREVIEW_SECRET) {
    return new Response('Invalid secret', { status: 401 })
  }
  if (!slug || !(await fetchDraft(slug))) {
    return new Response('Content not found', { status: 404 })
  }

  ;(await draftMode()).enable()
  redirect(`/blog/${encodeURIComponent(slug)}`)
}
```

```typescript
// app/api/preview/exit/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'

export async function GET() {
  ;(await draftMode()).disable()
  redirect('/')
}
```

## Read Drafts in the Page

```typescript
// app/blog/[slug]/page.tsx
import { draftMode } from 'next/headers'
import { notFound } from 'next/navigation'
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
import { fetchDraft } from '@/lib/draft'
import { DraftBody } from '@/components/draft-body' // your renderer for the editor document

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

  if ((await draftMode()).isEnabled) {
    const draft = await fetchDraft(slug)
    if (!draft) notFound()
    return (
      <article>
        <p>
          Preview ({draft.status}). <a href="/api/preview/exit">Exit preview</a>
        </p>
        <h1>{draft.title}</h1>
        <DraftBody doc={draft.body} />
      </article>
    )
  }

  let article
  try {
    article = await lynkow.contents.getBySlug(slug)
  } catch (error) {
    if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
    throw error
  }

  return (
    <article>
      <h1>{article.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: article.body }} />
    </article>
  )
}
```

With Draft Mode on, Next.js renders the page at request time for that browser only. Visitors keep the published, cached page.

## Security

- Give the token the `contents.view` permission only.
- Keep the token and the secret out of client code. Use them only in route handlers and Server Components.
- If the token leaks, regenerate it under **Settings > Developers > API**.

## Next Steps

- [Webhooks & Cache Revalidation](/sdk/advanced/webhooks-revalidation): refresh published pages when content changes
- [Visual Editor](/sdk/advanced/visual-editor): edit page blocks from inside the dashboard
- [Error Handling & Resilience](/sdk/advanced/error-handling): the errors the SDK path throws