Skip to content

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
  • 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), and body (rich text). If the names differ, adjust the code below

To load Hako CMS entries into a collection at build time, do the following.

  1. Write the environment’s address and the API key in .env in the site folder. Keep .env out of the repository.

    ターミナルウィンドウ
    HAKO_API_URL=https://<hostname>.hakocms.net
    HAKO_API_KEY=<API key>
  2. Write a collection that reads from Hako CMS in src/content.config.ts. Each item in the array that loader returns becomes one entry in the collection. Put the slug used in the URL in id.

    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 build
    loader: 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 id
    return 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, update schema too.

  3. 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.data is typed with the shape in schema.

  4. Build the site.

    ターミナルウィンドウ
    npx astro build

    dist/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.

  1. 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 list
    loadCollection: 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 }),
    };
  2. Write the post page in src/pages/posts/[slug].astro. You can output the HTML put in rendered as <Content /> with render.

    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 loadEntry returns undefined, getLiveEntry returns with LiveEntryNotFoundError in error. If you leave it, the page returns 500, so return 404.

  3. Open it with npx astro build && npx wrangler dev, and check that the post appears at http://localhost:8787/posts/<slug> and that a slug that does not exist returns 404.

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.

  • Collection read at build time: npx astro build finishes, and dist/posts/ has one folder per entry
  • Live collection: with wrangler dev, the post appears, and a slug that does not exist returns 404

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.