Skip to content

Use with a static site

On a static Astro site, you read Hako CMS entries at build time and build pages. The people who update content in the admin do not need to be engineers, and you can design the site freely with Astro. For how this differs from the other approaches, see Use Hako CMS with Astro.

  • An Astro site. Leave output at the default "static"
  • An API key with only the [読み取り](Read) permission. For how to issue one, see Create API keys and set permissions
  • The content type “posts” (collection) has the following fields. If the names differ, adjust the code below
    • title (text)
    • slug (text. Lowercase letters, digits, and hyphens used in the URL)
    • body (rich text)
  • The “posts” entries are [公開中](Published)

You use the API key only at build time. Do not put it in code sent to the browser.

To read Hako CMS entries from an Astro site, do the following.

  1. Create .env in the site folder and write the environment’s address and the API key. Add .env to .gitignore and keep it out of the repository.

    ターミナルウィンドウ
    HAKO_API_URL=https://<hostname>.hakocms.net
    HAKO_API_KEY=<API key>

    <hostname> is the part of the admin address https://<hostname>.hakocms.net. <API key> is the API key that starts with hako_.

  2. Write a function that reads the Content API in src/lib/hako.ts. You can read up to 100 entries at a time, so keep reading the rest until you reach total. With richText=html, you receive rich text as HTML.

    src/lib/hako.ts
    const base = import.meta.env.HAKO_API_URL;
    const key = import.meta.env.HAKO_API_KEY;
    export type Post = {
    sys: { id: string; publishedAt: string };
    title: string;
    slug: string;
    body: string; // An HTML string because of richText=html
    };
    type List<T> = { items: T[]; total: number };
    async function get<T>(path: string): Promise<T> {
    const res = await fetch(new URL(path, base), {
    headers: { Authorization: `Bearer ${key}` },
    });
    if (!res.ok) {
    throw new Error(`GET ${path}: ${res.status} ${await res.text()}`);
    }
    return res.json() as Promise<T>;
    }
    /** Read all published posts, newest publish date first */
    export async function getPosts(): Promise<Post[]> {
    const posts: Post[] = [];
    let total = Infinity;
    while (posts.length < total) {
    const query = new URLSearchParams({
    limit: "100",
    offset: String(posts.length),
    order: "-sys.publishedAt",
    richText: "html",
    });
    const page = await get<List<Post>>(`/api/v1/content/posts?${query}`);
    if (page.items.length === 0) break;
    posts.push(...page.items);
    total = page.total;
    }
    return posts;
    }
  3. Write the list page in src/pages/posts/index.astro.

    src/pages/posts/index.astro
    ---
    import { getPosts } from "../../lib/hako";
    const posts = await getPosts();
    ---
    <h1>お知らせ</h1>
    <ul>
    {posts.map((post) => (
    <li><a href={`/posts/${post.slug}/`}>{post.title}</a></li>
    ))}
    </ul>
  4. Write the page for each entry in src/pages/posts/[slug].astro. getStaticPaths builds one page per entry.

    src/pages/posts/[slug].astro
    ---
    import { getPosts, type Post } from "../../lib/hako";
    export async function getStaticPaths() {
    const posts = await getPosts();
    return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
    }));
    }
    const { post } = Astro.props as { post: Post };
    ---
    <article>
    <h1>{post.title}</h1>
    <div set:html={post.body} />
    </article>

    set:html outputs the HTML that Hako CMS returned as is. The headings, bold text, links, and images you wrote in the admin appear as they are.

  5. Build the site.

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

    You get one page per entry. Partway through the output, lines like the following appear (times and durations are omitted).

    generating static routes
    ├─ /posts/hello/index.html
    ├─ /posts/new-menu/index.html
    └─ /posts/index.html

A static site keeps the content it had when it was built. Rebuild the site when you publish an entry in the admin, unpublish it, or delete it.

  • If you host the site on Vercel or Netlify, use the webhook preset [Vercel(Deploy Hook)] or [Netlify(Build Hook)]. For how to set it up, see Set up webhooks. Even if you publish many entries in a row, notifications not yet sent are combined into one, so builds do not run over and over
  • If you host it elsewhere, use that host’s URL for starting a build as the webhook destination

When you create the webhook, also check [公開終了](Unpublish) under [通知するイベント](Events to notify). Only [エントリーの公開・公開中の更新](Entry published or published entry updated) and [エントリーの削除](Entry deleted) are checked at first. If you do not check [公開終了], pages of unpublished entries stay on the site until the next rebuild.

Also set HAKO_API_URL and HAKO_API_KEY as environment variables where you build.

  • npx astro build finishes, and dist/posts/ has one folder per entry
  • After you publish one entry in the admin and rebuild, its page is added
  • After you set that entry to [公開終了](Unpublish) and rebuild, its page is gone

If the build stops with GET /api/v1/content/posts…: 401, the API key is missing, wrong, or revoked. If it stops with 403, the API key does not have permission to read “posts”. On the [API キー](API keys) screen, check the key’s [読み取り](Read). If it stops with 404, the content type ID is wrong (compare it with the [エンドポイント](Endpoint) value on the screen). If it stops with 400 and says the response exceeded 5 MB, the article bodies are too large. Make the limit in getPosts smaller.