# Next.js와 Cache Components 사용

> "use cache" 함수 내에서 Kanorio 콘텐츠를 읽고 응답에서 각 태그를 지정하여 레코드 단위로 새로 고침하는 방법을 설명합니다.

> Markdown version of https://kanorio.com/ko/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/ko/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/ko/developers/guides/nextjs)와 같습니다. `cover_image`는 작성자가 고른 커버이며, 없으면 `null`입니다. 목록은 커버가 없을 때 `share_image`를 사용하고, 기사 페이지는 게시물에 커버가 있을 때 이를 표시하며, `generateMetadata`는 제목, canonical, robots, 공유 이미지를 `seoMetadata`에서 가져옵니다.

`generateMetadata`와 페이지는 동일한 인수로 `loadPost`를 호출하므로 게시물은 한 번만 읽힙니다. `generateStaticParams`가 없으면 페이지는 `<Suspense>` 내부에서 `params`를 읽어야 합니다. 이렇게 해도 빌드는 가능하지만, 게시물을 조회할 때 이미 응답이 시작된 상태이므로 존재하지 않는 게시물도 `200` 상태로 전송됩니다.

## 4. 재검증

Next.js 가이드의 5단계에 있는 라우트 핸들러를 그대로 사용하십시오. 이는 이벤트가 나열하는 모든 태그를 재검증합니다. 위의 태그를 사용하면 `item:<id>`가 이제 정확히 하나의 게시물과 일치하게 됩니다.
