Skip to content

Use with Cloudflare Workers

You run Astro pages on Cloudflare Workers and read Hako CMS entries when a page is opened. Published entries appear without rebuilding the site.

On other JavaScript runtimes (a Node.js server, Vercel, Netlify, and so on), the same code works if you switch the Astro adapter. The examples on this page are for Cloudflare Workers.

  • An Astro site and a Cloudflare account
  • 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 read Hako CMS entries when a page is opened, do the following.

  1. Add the Cloudflare adapter.

    ターミナルウィンドウ
    npx astro add cloudflare
  2. Set up astro.config.mjs as follows. Define HAKO_API_URL and HAKO_API_KEY as values read when a page is opened (Secrets). This keeps the values out of the build output.

    astro.config.mjs
    import { defineConfig, envField } from "astro/config";
    import cloudflare from "@astrojs/cloudflare";
    export default defineConfig({
    adapter: cloudflare({
    // Hako CMS transforms images, so do not use Cloudflare Images
    imageService: "passthrough",
    // Build prerendered pages in Node so they can read values from .env
    prerenderEnvironment: "node",
    }),
    // No sessions are used, so do not create a KV namespace
    session: false,
    env: {
    schema: {
    HAKO_API_URL: envField.string({ context: "server", access: "secret" }),
    HAKO_API_KEY: envField.string({ context: "server", access: "secret" }),
    },
    },
    });

    If you do not write imageService and session, the adapter creates settings that use Cloudflare Images and KV. For how to serve images, see Display images.

    If you do not write prerenderEnvironment, pages built at build time are built inside the Cloudflare runtime and cannot read values from .env. You need it when pages built at build time, such as the list, read Hako CMS.

  3. Write the values you use locally in both .dev.vars and .env. Pages built when opened read .dev.vars, and pages built at build time read .env. Add both to .gitignore and keep them 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_.

  4. Write functions that read the Content API in src/lib/hako.ts. getPostBySlug looks up one entry by slug, so it filters with where. getPosts is used on the list page built at build time. You can read up to 100 entries at a time, so keep reading the rest until you reach total.

    src/lib/hako.ts
    import { HAKO_API_URL, HAKO_API_KEY } from "astro:env/server";
    export type Post = {
    sys: { id: string; publishedAt: string | null };
    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, HAKO_API_URL), {
    headers: { Authorization: `Bearer ${HAKO_API_KEY}` },
    });
    if (!res.ok) {
    throw new Error(`GET ${path}: ${res.status} ${await res.text()}`);
    }
    return res.json() as Promise<T>;
    }
    // Add \ before " and \ in a where string, and wrap it in quotes
    const quote = (s: string) =>
    `"${s.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
    /** Read one post whose slug matches. If preview is true, read drafts */
    export async function getPostBySlug(
    slug: string,
    { preview = false } = {},
    ): Promise<Post | null> {
    const query = new URLSearchParams({
    where: `slug = ${quote(slug)}`,
    limit: "1",
    richText: "html",
    });
    if (preview) query.set("preview", "true");
    const page = await get<List<Post>>(`/api/v1/content/posts?${query}`);
    return page.items[0] ?? null;
    }
    /** 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;
    }

    Visitors can change the slug in the URL freely. If you put it in where without passing it through quote, a value that contains " makes the expression unreadable.

  5. Write the post page in src/pages/posts/[slug].astro. export const prerender = false makes only this page build when it is opened.

    src/pages/posts/[slug].astro
    ---
    export const prerender = false;
    import { getPostBySlug } from "../../lib/hako";
    const post = await getPostBySlug(Astro.params.slug ?? "");
    if (!post) {
    return new Response("Not found", { status: 404 });
    }
    // Tell caches they may reuse the same response for 60 seconds
    Astro.response.headers.set("Cache-Control", "public, max-age=60");
    ---
    <article>
    <h1>{post.title}</h1>
    <div set:html={post.body} />
    </article>

    Other pages are still built at build time. You can write the post list page with getPosts, as in step 3 of Use with a static site.

  6. Run it in the Cloudflare runtime locally. astro dev also works, but to check that it behaves the same as production, build it and open it with wrangler dev.

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

    Open http://localhost:8787/posts/<slug> and the post appears. A slug that does not exist returns 404.

  7. Put the Secrets in Cloudflare and deploy.

    ターミナルウィンドウ
    npx wrangler secret put HAKO_API_URL
    npx wrangler secret put HAKO_API_KEY
    npx astro build && npx wrangler deploy

    If you build in CI, also set HAKO_API_URL and HAKO_API_KEY as CI environment variables for the pages built at build time.

    When you run wrangler secret put, it asks you to enter the value.

When you use Cloudflare Workers, the Content API is called each time a page is opened. Hako CMS plans have a monthly data transfer limit. When you exceed the limit, delivery stops. There is no extra charge. For the amount in each plan, see the pricing page on the product site. On sites that are opened often, reuse the same response to reduce the number of calls.

  • Cache responses on Cloudflare. By default, Cloudflare Workers does not cache the responses a Worker returns. When you enable Cloudflare’s Workers Cache, it returns the same response without running the Worker for the time in Cache-Control. To enable it, write "cache": { "enabled": true } in the Wrangler configuration file (wrangler.jsonc). Once it is enabled, requests for static files also count as Workers requests. For pricing, check Cloudflare’s Workers Cache
  • Keep the cache time short. Published content is delayed only for the cache time. If you keep it short, like the 60 seconds in the example above, you need neither a rebuild nor a cache purge
  • Build pages that are opened often and rarely change, such as the post list and the top page, at build time (do not add prerender = false). Rebuild with a webhook when you publish
  • With wrangler dev, the post page appears, and a slug that does not exist returns 404
  • After you deploy, edit and publish an entry in the admin, then reopen the page after the cache time (60 seconds in the example above). The edited content appears

If the build stops with HAKO_API_URL is missing, the value is not in .env (environment variables in CI), or prerenderEnvironment: "node" is not written.

If a page returns 500, check the wrangler dev output or the Cloudflare Worker logs. HAKO_API_KEY is missing means the Secret is not set. GET /api/v1/content/posts…: 401 means the API key is missing, wrong, or revoked. 403 means the API key does not have permission to read “posts”. If it stops with 400 and says the response exceeded 5 MB, the article bodies are too large. Make the limit in getPosts smaller.