Preview drafts before publishing
You make it possible to check drafts written in the admin on the site before publishing. Production pages stay as built at build time, and only the preview pages are built on the server when they are opened.
Prerequisites
Section titled “Prerequisites”- You have completed steps 1–4 of Use with Cloudflare Workers. This page uses the
astro.config.mjsandsrc/lib/hako.tscreated there. If you built the site as in Use with a static site, replacesrc/lib/hako.tswith the one from step 4 of the server page. It also has agetPostswith the same name, so the list and post pages keep working as they are. Write the values in both.envand.dev.vars - An API key with the [読み取り](Read) and [プレビュー](Preview) permissions. Put this key in
HAKO_API_KEY. Whether drafts can be read is decided by the key’s permissions - A long secret string known only to the people allowed to see previews (
PREVIEW_SECRET). Use a random string of 32 characters or more
With a key that has the [プレビュー] permission, anyone can read drafts by adding preview=true. Do not build the site so that it simply adds preview=true to the call whenever the site URL has ?preview=true. In the design on this page, only people who know the secret string get a cookie, and drafts are read only when that cookie is present.
To add a draft preview, do the following.
-
Add
PREVIEW_SECRETtoenv.schemainastro.config.mjs.PREVIEW_SECRET: envField.string({ context: "server", access: "secret" }),Also add the value you use locally to
.dev.vars.ターミナルウィンドウ PREVIEW_SECRET=<secret string> -
Write the entry point to the preview in
src/pages/api/preview.ts. If the secret string matches, it sets a cookie and redirects to the preview page.src/pages/api/preview.ts import type { APIRoute } from "astro";import { PREVIEW_SECRET } from "astro:env/server";export const prerender = false;export const GET: APIRoute = ({ url, cookies, redirect }) => {const slug = url.searchParams.get("slug") ?? "";if (url.searchParams.get("secret") !== PREVIEW_SECRET || !slug) {return new Response("Forbidden", { status: 403 });}cookies.set("hako_preview", PREVIEW_SECRET, {path: "/preview",httpOnly: true,secure: true,sameSite: "lax",maxAge: 60 * 60, // 1 hour});return redirect(`/preview/posts/${encodeURIComponent(slug)}`, 302);}; -
Write the preview page in
src/pages/preview/posts/[slug].astro. Without the cookie, it returns403. With it, it reads the draft.src/pages/preview/posts/[slug].astro ---export const prerender = false;import { PREVIEW_SECRET } from "astro:env/server";import { getPostBySlug } from "../../../lib/hako";if (Astro.cookies.get("hako_preview")?.value !== PREVIEW_SECRET) {return new Response("Forbidden", { status: 403 });}const post = await getPostBySlug(Astro.params.slug ?? "", { preview: true });if (!post) {return new Response("Not found", { status: 404 });}// Do not keep drafts in the browser or on CloudflareAstro.response.headers.set("Cache-Control", "private, no-store");Astro.response.headers.set("X-Robots-Tag", "noindex");---<p>Preview (draft before publishing)</p><article><h1>{post.title}</h1><div set:html={post.body} /></article>If you use the same layout and components as the production post page, you can check it with the same look as when it is published.
-
Add the Secret to Cloudflare and deploy.
ターミナルウィンドウ npx wrangler secret put PREVIEW_SECRETnpx astro build && npx wrangler deploy
View a draft
Section titled “View a draft”The people who update content open the following URL.
https://<site domain>/api/preview?secret=<secret string>&slug=<slug><slug> is the slug value of the entry you want to check. You are redirected to the preview page, and the draft content appears. The cookie expires after 1 hour. When it expires, open the same URL again.
Anyone who knows the secret string can see drafts. Share it only among the people who update content. If it leaks, change it to a new string and set it again with wrangler secret put PREVIEW_SECRET.
Verify
Section titled “Verify”- Opening the preview page without the secret string returns
403 - Opening the URL above shows the content of an unpublished draft
- The production post page still shows the published content
Related
Section titled “Related”- Read drafts (preview): what
preview=truereturns - Create API keys and set permissions
- Use with Cloudflare Workers