# Next.js と Cache Components の利用

> "use cache" 関数内で Kanorio コンテンツを読み取り、レスポンスから各タグを付与して、レコード単位で更新する方法を解説します。

> Markdown version of https://kanorio.com/ja/developers/guides/nextjs-cache-components. Append `.md` to any developer docs URL for this format. Index: https://kanorio.com/llms.txt · MCP: https://app.kanorio.com/api/mcp
>
> Translated from the English original: https://kanorio.com/en/developers/guides/nextjs-cache-components.md

`cacheComponents: true` を設定すると、Next.js は `"use cache"` とマークされた内容をキャッシュし、読み取り後にキャッシュタグを追加できるようになります。Kanorio のレスポンスには独自のタグがリストされているため、投稿には `item:<id>` というタグが付けられます。これにより、特定の投稿を編集した際に、その投稿とそれが含まれるリストのみが更新され、他のデータは再取得されません。

このページは [Next.js ガイド](https://kanorio.com/ja/developers/guides/nextjs) のステップ 3 および 4 を置き換えるものです。環境変数、生成された型、Webhook ルート、ドラフトモード、および SEO ファイルは、ガイドの内容をそのまま使用してください。

## 1. 有効化

```ts
// next.config.ts
import { seoRewrites } from "@kanorio/sdk";

export default {
  cacheComponents: true,
  async rewrites() {
    return seoRewrites({ siteUrl: process.env.NEXT_PUBLIC_KANORIO_SITE_URL!, framework: "next" });
  },
};
```

## 2. "use cache" 内での読み取り

```ts
// lib/kanorio.ts
import { cacheLife, cacheTag } from "next/cache";
import { draftMode } from "next/headers";
import { frameworkCacheTags } from "@kanorio/sdk";

const SITE_URL = process.env.NEXT_PUBLIC_KANORIO_SITE_URL!;

export async function kanorio<T>(path: string): Promise<T | null> {
  "use cache";
  cacheLife("hours");
  const { isEnabled: isDraft } = await draftMode();
  const url = new URL(`/api/v1${path}`, SITE_URL);
  if (isDraft) url.searchParams.set("preview", "1");

  const res = await fetch(url, isDraft ? { headers: { "X-Kanorio-Preview": process.env.KANORIO_PREVIEW_TOKEN! } } : undefined);
  // The response lists what it used; tag after the read
  cacheTag(...frameworkCacheTags(res.headers));
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Kanorio ${res.status} for ${path}`);
  return (await res.json()) as T;
}
```

`frameworkCacheTags` は `X-Kanorio-Cache-Tags` を読み取り、Webhook ハンドラーが使用する `kanorio:` プレフィックスを追加します。`cacheLife("hours")` は Webhook が届かない場合のフォールバックとして機能します。ドラフトモードが有効な間、Next.js はキャッシュされた関数をリクエストごとに実行し、何も保存しないため、ドラフトは常に最新の状態が保たれます。

## 3. 投稿のレンダリング

リストページでは、パス以外を渡す必要はありません。

```tsx
// app/blog/page.tsx
import Link from "next/link";
import { image } from "@kanorio/sdk";
import { kanorio } from "@/lib/kanorio";
import type { KanorioCollectionsMap } from "@/types/kanorio";

export default async function BlogIndex() {
  const page = await kanorio<KanorioCollectionsMap["blog"]["list"]>(
    "/collections/blog/items?sort=-publishedAt&limit=20&fields=title,excerpt,cover_image,share_image"
  );
  return (
    <ul>
      {page?.data.map((post) => {
        // The cover the author picked, resized for a card. A post without one shows its share image (1200x630, ready to use)
        const cover = image.resolve(post.fieldData.cover_image, page.assets);
        const src = cover ? image.url(cover.url, { width: 800 }) : post.fieldData.share_image?.url;
        return (
          <li key={post.id}>
            {src && <img src={src} alt={cover?.alt ?? ""} loading="lazy" />}
            <Link href={post.path ?? `/blog/${post.slug}`}>{post.fieldData.title}</Link>
          </li>
        );
      })}
    </ul>
  );
}
```

投稿ページについては、`generateStaticParams` で投稿をリストアップします。Next.js はビルド時にこれらを事前レンダリングし、後から公開された投稿は初回アクセス時にレンダリングされます。存在しないスラッグには、正しく `404` ステータスが返されます。

```tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { image, seoMetadata } from "@kanorio/sdk";
import { toNextMetadata } from "@kanorio/sdk/next";
import { kanorio } from "@/lib/kanorio";
import type { KanorioCollectionsMap } from "@/types/kanorio";

type Params = { params: Promise<{ slug: string }> };

function loadPost(slug: string) {
  return kanorio<KanorioCollectionsMap["blog"]["single"]>(
    `/collections/blog/items/${encodeURIComponent(slug)}?expand=authors,categories&formats=html`
  );
}

export async function generateStaticParams() {
  const page = await kanorio<KanorioCollectionsMap["blog"]["list"]>("/collections/blog/items?sort=-publishedAt&limit=100&fields=title");
  return (page?.data ?? []).map((post) => ({ slug: post.slug }));
}

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const data = await loadPost((await params).slug);
  if (!data) return {};
  // Title, description, canonical, robots and the share image, by the rules the hosted site uses.
  // The share image is `fieldData.share_image`: Kanorio has picked it and cropped it the way the author framed it
  return toNextMetadata(seoMetadata(data.item));
}

export default async function BlogPost({ params }: Params) {
  const data = await loadPost((await params).slug);
  if (!data) notFound();

  const { item, assets } = data;
  // The cover is optional. It is an asset id: `assets` has its URL, size and alt text
  const cover = image.resolve(item.fieldData.cover_image, assets);
  return (
    <article>
      <h1>{item.fieldData.title}</h1>
      {cover && (
        <img
          src={image.url(cover.url, { width: 1200 })}
          srcSet={image.srcSet(cover.url)}
          sizes="(min-width: 800px) 768px, 100vw"
          alt={cover.alt ?? ""}
          width={cover.width ?? undefined}
          height={cover.height ?? undefined}
        />
      )}
      {item.contentHtml && <div dangerouslySetInnerHTML={{ __html: item.contentHtml }} />}
    </article>
  );
}
```

リストと投稿ページでのカバー画像の扱いは [Next.js ガイド](https://kanorio.com/ja/developers/guides/nextjs) と同じです。`cover_image` は著者が選んだカバー画像で、ない場合は `null` です。リストではカバー画像がなければ `share_image` を使い、投稿ページではカバー画像がある場合に表示し、`generateMetadata` はタイトル、canonical、robots、共有画像を `seoMetadata` から取得します。

`generateMetadata` とページは同じ引数で `loadPost` を呼び出すため、投稿は一度だけ読み取られます。`generateStaticParams` を使用しない場合、ページは `<Suspense>` 内で `params` を読み取る必要があります。これでもビルドは可能ですが、投稿が検索される時点でレスポンスがすでに開始されているため、存在しない投稿でも `200` ステータスで送信されてしまいます。

## 4. 再検証

Next.js ガイドのステップ 5 のルートハンドラーをそのまま使用してください。これはイベントがリストするすべてのタグを再検証します。上記のタグを使用することで、`item:<id>` は特定の 1 つの投稿と正確に一致するようになります。
