Blog
My posts live in Sanity, a hosted CMS, and I write them in a hosted Studio. Publishing a post needs no commit, build, release or deployment. The code, schema and components ship through the normal release pipeline.
How a post goes live
- I publish the post in the Studio.
- Sanity calls
POST /api/revalidate/blogwith a signed body. - The route verifies the signature against
SANITY_WEBHOOK_SECRET, rejects one whose timestamp is more than five minutes from now (Sanity retries a failed delivery twice, 30 seconds apart, so a real one is about a minute old at worst), and callsrevalidateTag("blog", { expire: 0 }). A request that was rejected for its age is not retried, and the one hourrevalidatebelow corrects the page. - The next request to
/blogor/blog/<slug>renders fresh content. Unpublishing and editing take the same path.
Every Sanity read carries the blog cache tag and a one hour revalidate, so a missed webhook corrects itself within the hour. Reads go to the Sanity API instead of its CDN (useCdn: false). A webhook can fire before the CDN has the change, and a cache refilled from the CDN at that moment would keep the old result for the whole hour. The Next.js cache means this adds few API requests.
Markdown versions and llms.txt
Like every other page, the blog has Markdown alternates: /blog/md is the index and /blog/<slug>/md is each post. They follow the HTML pages. The webhook revalidates them through the same blog tag, they return 404 while there are no posts, and on staging they include drafts. Each HTML page links its alternate with <link rel="alternate" type="text/markdown">.
/llms.txt gets a “Writing” section with the index and every post, and the home Markdown (/md) links them too. With no posts, neither mentions the blog.
portableTextToMarkdown in src/lib/markdown/portableText.ts converts a post body. It handles paragraphs, h2 and h3 (below the page’s own H1), quotes, lists with nesting, strong, emphasis, inline code, links, images with alt text and fenced code blocks, with a block’s line notes removed. Block types it does not know are left out, and so is an image without alt text.
The slug md is reserved, because /blog/md is the index’s Markdown version. The Studio rejects it.
The index
/blog lists posts newest first as glass plates. The newest post is a wide plate, with its cover beside the text from the tablet width up. A post with no cover draws its own art from the theme tokens (an accent wash, hairlines and the first letter of the title), so the grid keeps its shape.
From three posts the page also shows a search field and one chip per tag. Search matches every word you type, in any order, against the title, excerpt and tags. A chip narrows the list to one tag, and the two combine. The count under the field is a polite live region, so a screen reader hears the result of typing. When nothing matches, a message and a “Clear filters” button replace the list. With fewer than three posts there are no filters, because there is nothing to narrow.
Filtering runs in the browser over the posts the page already loaded. getPosts returns every body, so the route passes toSummary copies without the body to the client component. filterPosts in src/lib/blog/filter-posts.ts holds the matching rules and has its own tests. The search is not in the URL and does not survive a reload.
The post page
A post leads with its date and reading time, then the title set large, the excerpt as a lede, and the tags, over the same ink rule the other sub-pages use. The cover sits wide under it, and the body follows in a column offset from the left edge on a wide screen. The title is the page’s only h1.
The reading time counts the words in the body’s text blocks at 220 words a minute and rounds to whole minutes, with a minimum of one. Code blocks and images are skipped. readingMinutes in src/lib/blog/reading-time.ts does the count and ignores any block that is malformed.
The page ends on the newer and older posts as two glass plates, each a label, a title and a date. The newest post has no newer plate and the oldest has no older one, and a post with neither draws no section. adjacentPosts in src/lib/blog/adjacent-posts.ts picks them from the list of published posts, newest first. A draft that is not published yet is not in that list, so a previewed draft has no neighbours.
Where things live
studio/is the Studio package. It has its ownpackage.jsonand lockfile, likedocs-site/, and is never imported by the app. It deploys to a*.sanity.studioURL withpnpm --dir studio deploy.src/lib/blog/holds the Sanity client, the GROQ queries, the mapper from Sanity documents toBlogPost, the webhook check, the RSS builder and the code highlighter.src/lib/code-block/holds the code block settings, line notes and model.src/components/CodeBlock/draws it, for the blog and for assistant answers. See Code blocks.src/app/blog/holds/blog,/blog/[slug]and/blog/rss.xml.src/app/api/revalidate/blogis the webhook.src/app/api/draftturns Draft Mode on and off.src/lib/structured-data/buildsBlogPostingJSON-LD and serializes it safely for a<script>tag. It is the shared helper for structured data on other routes.
I read with @sanity/client rather than next-sanity. next-sanity declares the full sanity Studio package as a peer, which pnpm installs into the app.
The post schema
A post has a title, a slug, an excerpt (up to 240 characters), a published date, an optional cover image, a body and optional tags.
- Every image, including the cover, requires alt text. The app does not render an image without it.
- The body is Portable Text: paragraphs,
h2andh3, quotes, bulleted and numbered lists, strong, emphasis, inline code, links, images and code blocks. - The dataset is untrusted input: the Studio validates a post, but a write token does not. The renderer therefore enforces the same rules itself. A link renders only for an absolute
http,httpsormailtoURL, and anything else shows as plain text (safeHrefinsrc/utils). A code block’s token markup comes only from the server-side highlighter, so a storedhtmlorcodeBlockfield is dropped, and a code block whose source is not a string renders nothing. See Code blocks. - Code blocks are highlighted on the server with Shiki and drawn by
CodeBlock, with a filename, copy button, highlighted lines and diffs. Authoring, defaults, limits and security rules are in Code blocks.
When the blog is hidden
With zero published posts, /blog and /blog/rss.xml return 404, the sitemap lists no blog URLs and the footer shows no “Writing” link. The link appears after the first post is published and the webhook has run.
When Sanity is unavailable
- During
next build, a failed request resolves to an empty result. The build passes and the blog stays hidden. - At runtime, a failed request throws. A page that is revalidating keeps serving its last good render, so an outage or an exceeded quota does not turn
/bloginto a 404. - A post that was never rendered returns an error until Sanity answers, because there is no earlier render to fall back to.
The data layer logs each distinct failure once with a [blog] prefix.
Environment variables
| Variable | Where | Purpose |
|---|---|---|
NEXT_PUBLIC_SANITY_PROJECT_ID | App | Sanity project ID. Unset means the blog is off and the build makes no request. |
NEXT_PUBLIC_SANITY_DATASET | App | Dataset name. Defaults to production. |
SANITY_API_READ_TOKEN | App, server | Viewer token. Lets Draft Mode read drafts and check Studio preview links. Never sent to the browser. |
SANITY_WEBHOOK_SECRET | App, server | Signs webhook calls. Without it the webhook rejects every request. |
SANITY_STUDIO_PROJECT_ID | Studio | Project ID for sanity dev, build and deploy. Required. |
SANITY_STUDIO_DATASET | Studio | Dataset name. Defaults to production. |
SANITY_STUDIO_HOST | Studio | Hostname for sanity deploy, giving https://<host>.sanity.studio. |
SANITY_STUDIO_SITE_URL | Studio | Site origin for the preview link. Defaults to http://localhost:3000. |
The app variables are validated in src/config/env. All are optional, so pnpm build passes without them and without SKIP_ENV_VALIDATION.
Setup checklist
These steps need my Sanity account.
- Create a project on the Free plan at sanity.io with a public
productiondataset. - Set
SANITY_STUDIO_PROJECT_IDandSANITY_STUDIO_HOST, then runpnpm --dir studio deploy. Choose the sign-in provider (GitHub or Google) in the project’s member settings. - Create a viewer token and set it as
SANITY_API_READ_TOKEN. - Create a webhook in the project’s API settings:
- URL:
https://<site>/api/revalidate/blog - Trigger on create, update and delete, with the filter
_type == "post"and the projection{_id} - Secret: the value of
SANITY_WEBHOOK_SECRET
- URL:
- Set
NEXT_PUBLIC_SANITY_PROJECT_IDin the hosting environment. For the Studio’s preview link, setSANITY_STUDIO_SITE_URLwhen you runsanity deploy. No preview secret is needed. - For backups, create a token with read access to the dataset. Add it as the repository secret
SANITY_BACKUP_TOKEN, and add the repository variableSANITY_PROJECT_ID.
Drafts on staging
The staging deployment (NEXT_PUBLIC_APP_ENV=staging) shows drafts as well as published posts, so a post can be checked on the real site before it goes live. Every blog read there uses the drafts perspective with SANITY_API_READ_TOKEN, and the result is cached for 60 seconds. A draft appears on /blog, /blog/<slug>, the feed, the sitemap and the footer link within about a minute of saving. A post with both a draft and a published version shows the draft.
Production and local development read published content only, even when the token is set. Staging falls back to published content when the token is missing. Staging is behind Vercel Deployment Protection, so only signed-in team members can see the drafts. A draft with no published date shows its creation date.
Set SANITY_API_READ_TOKEN and NEXT_PUBLIC_SANITY_PROJECT_ID in the staging environment in Vercel.
Draft preview
In the Studio, the document menu offers an open-preview action. Each time it runs, the Studio stores a secret in the dataset as a draft document, under the editor’s own login, and puts it in the link: /api/draft?sanity-preview-secret=...&sanity-preview-pathname=/blog/<slug>. The secret expires after one hour.
/api/draft checks that secret against the dataset with the read token, using @sanity/preview-url-secret. A link without a valid secret gets a 401. When it is valid, the route turns on Draft Mode and redirects to the path, which only /blog and /blog/<slug> can be. In Draft Mode the post is read with the drafts perspective and the read token, with no caching. /api/draft/disable turns it off.
No reusable credential is shipped in the Studio JavaScript, because only a signed-in editor can create a valid secret.
Free plan limits
The figures below were taken from sanity.io/pricing when issue #340 was written. Sanity changes limits without notice, so check the pricing page before relying on them.
- 20 seats, 10,000 documents, 2 datasets (public only) and 2 GROQ webhooks
- 1 million API CDN requests and 250,000 API requests per month
- 100 GB bandwidth and 100 GB assets
The Free plan has hard caps. Exceeding the API quota blocks public API access. Pages that are already rendered keep serving. Revalidation then fails, so new and edited posts do not appear until the quota resets or the plan changes. To recover, check usage in the project’s dashboard, then either wait for the reset, reduce requests, or upgrade the plan.
Backup and restore
.github/workflows/sanity-backup.yml exports the dataset every Monday and on manual runs. The archive is kept for 90 days as a workflow artifact. The workflow ends without failing when SANITY_PROJECT_ID or SANITY_BACKUP_TOKEN is unset.
To restore, download the artifact, then import it:
gh run download <run-id> --repo <owner>/<repo> --dir backup
pnpm --dir studio exec sanity dataset import backup/backup.tar.gz production --replace--replace overwrites documents that share an ID with the archive. Use --missing to add only what is absent.
Pipeline
A change under studio/ does not rebuild staging, because studio/ is in NON_APP_PATHS in scripts/deploy/vercel-ignore.sh. CI runs type-check and build for the Studio when files under studio/ change.
Writing posts with agents
Four repo skills in .claude/skills/ take a post from an idea to a Sanity draft. Each stops for my approval, and none of them publishes.
| Skill | Run it to | Writes to .drafts/<slug>/ |
|---|---|---|
blog-brief | screen an idea, research sources into an evidence ledger, and outline a post | brief.md, ledger.md, outline.md |
blog-draft | write the text from an approved outline | draft.md |
blog-review | fact-check claims, run code samples, and check editorial and safety issues | review.md |
blog-publish | convert the draft to the post schema and create a Sanity draft | post.json, publish-checklist.md |
Run them in that order, for example “use blog-brief to plan a post about X”. Each skill reads brief.md, checks that the earlier gate is recorded and refuses to continue otherwise. The shared rules, states and templates are in .claude/skills/shared/blog/.
- I approve the topic, the outline and the draft. A separate message that names the post and says to publish is the only thing that lets
blog-publishpublish it. Approving the draft does not count. blog-publishcreates adrafts.*document through the Sanity connector when the session has it, and otherwise leavespost.jsonfor an import in the Studio. It never patches or publishes a live document without that message.- A fact without a source stays
[UNVERIFIED], andblog-publishrefuses a draft that still has one. It checks for markers before converting, and never strips one. - The draft approval and
review.mdrecord the SHA-256 ofdraft.md. Editing the draft after either voids both, andblog-publishstages only a draft whose current hash matches both. Claims about the author come only from my own words or from project source and history. .drafts/<slug>/is committed on a feature branch and holds no credentials, customer material or unreleased employer information. Prettier ignores it.- To correct a live post,
blog-publishcreates a new draft version and records the change in the checklist’s Corrections table. The same publish message is needed.
.drafts/example-uncached-reads/ is a worked example with state dry-run: brief, ledger, outline, draft, review and post.json for a post that was never sent to Sanity.
Schema, Portable Text and GROQ questions belong to the sanity-best-practices skill. These skills only add the editorial steps around it.