はじめに
Astro
Kanorioのコンテンツを使用して高速なAstroサイトを構築しましょう。静的またはサーバーレンダリング、公開時の再ビルド、SEOファイル、エッジリダイレクトに対応しています。
AstroはデフォルトでJavaScriptを出力しないため、ブランドサイトやブログに適しています。コンポーネントのフロントマターで fetch を使用してKanorioのコンテンツを読み込みます。静的サイトの場合はビルド時に、サーバーアダプターを使用する場合はリクエストごとに読み込みます。
1. 環境変数
# .env PUBLIC_KANORIO_SITE_URL="https://s-xxxxxxxxxxxx.kanorio.com"
サイト設定 › 開発者 から永続的なシステムURLを使用してください。
2. コレクションの一覧取得
--- // src/pages/projects.astro const SITE_URL = import.meta.env.PUBLIC_KANORIO_SITE_URL; const res = await fetch(`${SITE_URL}/api/v1/collections/projects/items?sort=-publishedAt&limit=20`); const { data, assets } = await res.json(); --- <section> <h1>Projects</h1> {data.map((item) => { const cover = assets[item.fieldData.cover]; return ( <article> {cover && <img src={cover.url} alt={cover.alt ?? ""} width={cover.width} height={cover.height} loading="lazy" />} <h2>{item.fieldData.title}</h2> <p>{item.fieldData.summary}</p> </article> ); })} </section>
3. ブログ記事
静的ビルドの場合、getStaticPaths は nextCursor を使用してブログの全ページを巡回します。
--- // src/pages/blog/[slug].astro const SITE_URL = import.meta.env.PUBLIC_KANORIO_SITE_URL; export async function getStaticPaths() { const siteUrl = import.meta.env.PUBLIC_KANORIO_SITE_URL; const slugs = []; let cursor = null; do { const url = new URL(`${siteUrl}/api/v1/collections/blog/items`); url.searchParams.set("fields", "title"); url.searchParams.set("limit", "100"); if (cursor) url.searchParams.set("cursor", cursor); const page = await (await fetch(url)).json(); slugs.push(...page.data.map((post) => post.slug)); cursor = page.hasMore ? page.nextCursor : null; } while (cursor); return slugs.map((slug) => ({ params: { slug } })); } const { slug } = Astro.params; const res = await fetch(`${SITE_URL}/api/v1/collections/blog/items/${encodeURIComponent(slug)}?expand=authors,categories&formats=html`); if (!res.ok) return Astro.redirect("/404"); const { item, assets } = await res.json(); const cover = item.fieldData.cover_image ? assets[item.fieldData.cover_image] : null; --- <article> <h1>{item.fieldData.title}</h1> {cover && <img src={cover.url} alt={cover.alt ?? ""} />} {item.toc?.length > 0 && ( <nav aria-label="Contents"> <ul>{item.toc.map((h) => <li data-level={h.level}><a href={`#${h.id}`}>{h.label}</a></li>)}</ul> </nav> )} <div class="prose" set:html={item.contentHtml} /> </article>
4. フォームと更新
- フォーム: Elementsの
<kanorio-form>を使用するか、フォーム で説明されているチャレンジおよび送信エンドポイントを使用します。許可されたオリジンにドメインを追加してください。 - 静的ビルド: ホスト側でデプロイフックを作成し、サイト設定 › Webhooks にWebhookとして追加して、コレクションおよびページイベントを購読します。公開するたびに再ビルドがトリガーされます。
- サーバーレンダリング:
@astrojs/cloudflareまたは@astrojs/nodeを使用する場合、リクエストごとに読み込み、X-Kanorio-Cache-Tagsレスポンスヘッダーでキャッシュします。createRevalidateHandlerで構築されたWebhookハンドラーは、data.cacheTags内のタグをパージします(同じ語彙を使用します。詳細は Webhooks を参照してください)。
5. SEOファイル
Astroにはプロキシ書き換え機能がなく、リダイレクトを行うとクローラーが別のドメインに転送されてしまいます。代わりにエンドポイントからファイルを配信してください。seoRewrites は各パスのソースURLを返します。
// src/lib/kanorio-seo.ts import { seoRewrites } from "@kanorio/sdk"; const targets = seoRewrites({ siteUrl: import.meta.env.PUBLIC_KANORIO_SITE_URL, framework: "astro" }); export async function proxySeoFile(path: string): Promise<Response> { const res = await fetch(targets[path]); return new Response(res.body, { status: res.status, headers: { "Content-Type": res.headers.get("Content-Type") ?? "text/plain; charset=utf-8" }, }); }
// src/pages/robots.txt.ts, and the same for sitemap.xml, llms.txt, llms-full.txt and feed.xml import { proxySeoFile } from "../lib/kanorio-seo"; export const GET = () => proxySeoFile("/robots.txt");
fetchDeliveryJsonLd を使用して各ページにJSON-LDを追加します。
--- import { fetchDeliveryJsonLd } from "@kanorio/sdk"; const jsonLd = await fetchDeliveryJsonLd({ siteUrl: import.meta.env.PUBLIC_KANORIO_SITE_URL, path: Astro.url.pathname }); --- {jsonLd && <script type="application/ld+json" set:html={jsonLd.scriptJson} />}
6. リダイレクトとクローラーのルール
サーバーアダプターを使用する場合、ミドルウェア内で管理画面のリダイレクト設定とAIクローラーのルールを適用し、IndexNowキーファイルを配信します。
// src/middleware.ts import { defineMiddleware } from "astro:middleware"; import { createKanorioMiddleware } from "@kanorio/sdk/edge"; const kanorioEdge = createKanorioMiddleware({ siteUrl: import.meta.env.PUBLIC_KANORIO_SITE_URL }); export const onRequest = defineMiddleware(async (context, next) => { const ctx = context.locals.runtime?.ctx; // Cloudflare adapter only const response = await kanorioEdge.handleRequest(context.request, { waitUntil: ctx ? (promise) => ctx.waitUntil(promise) : undefined, }); return response ?? next(); });
静的ビルドではミドルウェアを実行できません。ホスト側でリダイレクトを設定し、/{key}.txt を https://{site}/api/v1/seo/indexnow-key.txt に転送してください。ミドルウェアは完全一致パスのみを対象とするため、ワイルドカードリダイレクトは astro.config の redirects に追加してください。
7. アクセス解析
レイアウトでElementsスクリプトを一度読み込み、解析要素を追加します。
<script type="module" src="https://cdn.kanorio.com/elements/v1/kanorio-elements.js"></script> <kanorio-analytics site-url="https://s-xxxxxxxxxxxx.kanorio.com"></kanorio-analytics>
ページビュー、リファラー、キャンペーンパラメーター、AIアシスタントからの訪問が管理画面のアクセス解析に表示されます。