开始使用
Next.js 与 Cache Components
在 "use cache" 函数中读取 Kanorio 内容,从响应中标记每次读取,并一次刷新单条记录。
当设置 cacheComponents: true 时,Next.js 会缓存您标记为 "use cache" 的内容,并允许您在读取后添加缓存标签。Kanorio 的响应会列出其专属标签,因此文章会被标记为自身的 item:<id>,编辑单篇文章时仅会刷新该文章及其所属的列表,其余内容皆不会重新获取。
本页面取代了 Next.js 指南 中的步骤 3 和步骤 4。环境变量、生成的类型、Webhook 路由、草稿模式以及 SEO 文件皆保持不变。
1. 启用功能
// 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" 中读取
// 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. 渲染文章
列表页面无需传递任何参数,仅需路径:
// 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 会在构建时预先渲染这些页面,并会在首次访问时渲染后续发布的文章;若 slug 不存在,则会返回真实的 404 状态:
// 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 指南 相同:cover_image 是作者选择的封面,没有时为 null。列表在没有封面时改用 share_image,文章页面在文章有封面时显示它,generateMetadata 则由 seoMetadata 取得标题、规范网址、robots 与分享图片。
generateMetadata 与页面会使用相同的参数调用 loadPost,因此文章仅会被读取一次。若没有 generateStaticParams,页面必须在 <Suspense> 内读取 params;虽然这样也能构建,但当系统查询文章时响应已经开始,因此丢失的文章会以 200 状态码送出。
4. 重新验证
请保留 Next.js 指南步骤 5 中的路由处理程序。它会重新验证事件所列出的每个标签;通过上述标签,item:<id> 现在会精确对应到单篇文章。