Use with content collections
You load Hako CMS entries into Astro content collections. From your pages, you can use them with getCollection, just like Markdown collections.
There are two kinds of collections.
| Collection | When it reads | When to use |
|---|---|---|
Content collection (src/content.config.ts) |
At build time | When you use a static site |
Live collection (src/live.config.ts) |
When a page is opened | When you use Cloudflare Workers |
Prerequisites
Section titled “Prerequisites”- An API key with the [読み取り](Read) permission. For how to issue one, see Create API keys and set permissions
- The content type “posts” (collection) has the fields
title(text),slug(text), andbody(rich text). If the names differ, adjust the code below
Fetch at build time
Section titled “Fetch at build time”To load Hako CMS entries into a collection at build time, do the following.
-
Write the environment’s address and the API key in
.envin the site folder. Keep.envout of the repository.ターミナルウィンドウ HAKO_API_URL=https://<hostname>.hakocms.netHAKO_API_KEY=<API key> -
Write a collection that reads from Hako CMS in
src/content.config.ts. Each item in the array thatloaderreturns becomes one entry in the collection. Put theslugused in the URL inid.src/content.config.ts import { defineCollection } from "astro:content";import { z } from "astro/zod";const base = import.meta.env.HAKO_API_URL;const key = import.meta.env.HAKO_API_KEY;type Post = { sys: { id: string }; title: string; slug: string; body: string };const posts = defineCollection({// Read all published posts on every buildloader: async () => {const items: Post[] = [];let total = Infinity;while (items.length < total) {const query = new URLSearchParams({limit: "100",offset: String(items.length),order: "-sys.publishedAt",richText: "html",});const url = new URL(`/api/v1/content/posts?${query}`, base);const res = await fetch(url, {headers: { Authorization: `Bearer ${key}` },});if (!res.ok) throw new Error(`posts: ${res.status}`);const page = (await res.json()) as { items: Post[]; total: number };if (page.items.length === 0) break;items.push(...page.items);total = page.total;}// Put the slug used in the URL in idreturn items.map((p) => ({ id: p.slug, title: p.title, body: p.body }));},schema: z.object({ title: z.string(), body: z.string() }),});export const collections = { posts };If an entry does not match the shape written in
schema, the build stops. When you change fields in Hako CMS, updateschematoo. -
Write the post page in
src/pages/posts/[id].astro.src/pages/posts/[id].astro ---import { getCollection } from "astro:content";export async function getStaticPaths() {const posts = await getCollection("posts");return posts.map((post) => ({ params: { id: post.id }, props: { post } }));}const { post } = Astro.props;---<article><h1>{post.data.title}</h1><div set:html={post.data.body} /></article>post.datais typed with the shape inschema. -
Build the site.
ターミナルウィンドウ npx astro builddist/posts/gets one folder per entry. Setting up a rebuild when you publish is the same as “Rebuild when you publish” in Use with a static site.
Fetch when a page is opened (live collections)
Section titled “Fetch when a page is opened (live collections)”A live collection reads from Hako CMS each time a page is opened. This assumes you have completed steps 1–4 of Use with Cloudflare Workers, and uses the getPostBySlug created there.
-
Write a live collection that reads one entry in
src/live.config.ts.src/live.config.ts import { defineLiveCollection } from "astro:content";import type { LiveLoader } from "astro/loaders";import { getPostBySlug, type Post } from "./lib/hako";type PostData = { title: string; body: string };const hakoPosts: LiveLoader<PostData, { slug: string }> = {name: "hako-posts",// This example does not use the listloadCollection: async () => ({ entries: [] }),loadEntry: async ({ filter }) => {try {const post: Post | null = await getPostBySlug(filter.slug);if (!post) return undefined;return {id: post.slug,data: { title: post.title, body: post.body },rendered: { html: post.body },};} catch (e) {return { error: e as Error };}},};export const collections = {posts: defineLiveCollection({ loader: hakoPosts }),}; -
Write the post page in
src/pages/posts/[slug].astro. You can output the HTML put inrenderedas<Content />withrender.src/pages/posts/[slug].astro ---export const prerender = false;import { getLiveEntry, render } from "astro:content";const { entry, error } = await getLiveEntry("posts", {slug: Astro.params.slug ?? "",});// Not found also goes into error (named LiveEntryNotFoundError)if (error?.name === "LiveEntryNotFoundError" || !entry) {return new Response("Not found", { status: 404 });}if (error) throw error;const { Content } = await render(entry);---<article><h1>{entry.data.title}</h1><Content /></article>When
loadEntryreturnsundefined,getLiveEntryreturns withLiveEntryNotFoundErrorinerror. If you leave it, the page returns500, so return404. -
Open it with
npx astro build && npx wrangler dev, and check that the post appears athttp://localhost:8787/posts/<slug>and that aslugthat does not exist returns404.
Live collections also call the Content API each time a page is opened. Data transfer works the same as in “Cache and data transfer” in Use with Cloudflare Workers.
Verify
Section titled “Verify”- Collection read at build time:
npx astro buildfinishes, anddist/posts/has one folder per entry - Live collection: with
wrangler dev, the post appears, and aslugthat does not exist returns404
If the build stops with posts: 401, the API key is missing, wrong, or revoked. posts: 403 means the API key does not have permission to read “posts”. posts: 400 may mean a single response exceeded 5 MB. Make limit smaller.
Related
Section titled “Related”- Use Hako CMS with Astro: how to choose an approach
- Use with a static site
- Use with Cloudflare Workers
- Filter, sort, and paginate