Get started
Next.js with Cache Components
Read Kanorio content inside "use cache" functions, tag each read from the response, and refresh one record at a time.
With cacheComponents: true, Next.js caches what you mark with "use cache" and lets you add cache tags after a read. Kanorio's responses list their own tags, so a post is tagged with its own item:<id>, and editing one post refreshes that post and the lists it appears in. Nothing else is fetched again.
This page replaces steps 3 and 4 of the Next.js guide. Environment variables, generated types, the webhook route, draft mode and the SEO files stay as they are there.
1. Turn it on
// 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. Read inside "use cache"
// 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 reads X-Kanorio-Cache-Tags and adds the kanorio: prefix the webhook handler uses. cacheLife("hours") is the fallback for a webhook that never arrives. While draft mode is on, Next.js runs cached functions on every request and stores nothing, so drafts are always fresh.
3. Render posts
The list page has nothing to pass but the path:
// 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> ); }
For the post page, list the posts in generateStaticParams. Next.js prerenders those at build time and renders a post published later on its first visit, and an unknown slug gets a real 404 status:
// 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> ); }
The list and the article page treat the cover as in the Next.js guide: cover_image is the cover the author picked, or null. The list falls back to share_image, the article page draws the cover when the post has one, and generateMetadata gets the title, canonical, robots and share image from seoMetadata.
generateMetadata and the page call loadPost with the same arguments, so the post is read once. Without generateStaticParams the page has to read params inside <Suspense>; that builds too, but the response has already started when the post is looked up, so a missing post is sent with status 200.
4. Revalidate
Keep the route handler from step 5 of the Next.js guide. It revalidates every tag an event lists; with the tags above, item:<id> now matches exactly one post.