Why move content out of TypeScript files at all

Until October 2026, every article on this site lived in two TypeScript arrays: src/data/blog.ts (18 posts) and src/data/guides.ts (12 guides). That setup is hard to beat on cost and safety. Hosting is static, and the BlogPost type makes the compiler reject an article that is missing its FAQ, citations, or author note.

It also has three real costs:

  • Publishing needs an IDE. Every typo fix is a commit, a push, and a full Vercel build.
  • AI drafts need git automation. An agent that writes a draft has to open a branch and a pull request against a 2,000-line data file.
  • No drafts, previews, or scheduling. A post is either merged or it does not exist.

A CMS is not the only fix, so I compared three options before writing any code:

Why move content out of TypeScript files at all
OptionAI drafts + reviewPublish without IDESchedulingKeeps compile-time content rulesNew infrastructure
Status quo + agent opens a GitHub PRYes (PR review)NoNoYesNone
Git-backed CMS (Keystatic, TinaCMS)PartialYesLimitedYesMinimal
Payload 3 + PostgresYes (draft queue)YesYesNo, must re-implementDatabase, migrations, backups

Payload won because scheduled publishing, in-layout preview, and an API-first draft queue were hard requirements. The accepted cost was explicit: compile-time checks become runtime validation, and the site takes on database operations. The plan also wrote down when to undo the decision: if the AI drafting pipeline is ever shelved, the first option delivers most of the value at almost no cost.

Embedding Payload in the same Next.js app

Payload 3 installs into an existing Next.js App Router project instead of running as a separate service, so the admin lives at /admin on the same deployment. The versions that shipped were Next.js 16.3.8 and Payload 3.90.2, pinned exactly.

Payload needs its own root <html> layout, which means the whole site moves into a route group:

code
src/app/├── (frontend)/   ← every existing page, route handler, feed and llms file│   └── layout.tsx└── (payload)/    ├── layout.tsx    ├── admin/[[...segments]]/page.tsx    └── cms-api/[...slug]/route.ts

Route groups do not change URLs, but this step touches every file path, so it went into its own pull request with its own parity check. It had three side effects worth knowing about before you start:

  1. Some metadata files must stay at the `app/` root: favicon.ico, apple-icon.png, manifest.ts, robots.ts, and sitemap.ts.
  2. Unmatched URLs need `global-not-found.tsx`. With two root layouts there is no layout left to wrap a 404, so the site's <html> shell was extracted into a shared component used by both the frontend layout and the global not-found page.
  3. Open Graph image URLs gained a hash suffix. Metadata image routes inside a route group get a suffix derived from the parent path (/blog/x/opengraph-image became /blog/x/opengraph-image-1g8epz), and the old URL returned 404. Rewrites in next.config.ts now map all 9 legacy patterns to the new routes, so links already shared on social platforms keep resolving.

The site already served 12 public API routes under /api, documented in an OpenAPI spec. Payload's default REST catch-all would have captured every unmatched /api/* path, so it was moved with one line, routes: { admin: "/admin", api: "/cms-api" }. GraphQL is disabled, and robots.txt disallows /admin, /cms-api, and /preview.

One reader and one flag for the content source

Sixteen files read articles directly: page routes, Open Graph images, the sitemap, the RSS feed, both llms files, tool pages that list related posts, and the search palette. All of them now call a single service module, and one environment variable decides where that module reads from:

TypeScript
type ContentSource = "static" | "cms";export function contentSource(): ContentSource {  const value = process.env.CONTENT_SOURCE ?? "static";  if (value !== "static" && value !== "cms") {    throw new Error(`CONTENT_SOURCE must be "static" or "cms", got "${value}".`);  }  return value;}

This made the risky part reversible. The consumer swap merged while production still read the TypeScript files. Going live meant changing an environment variable and redeploying the same commit, and rollback is the same action in reverse.

Diagram: 16 consumers read articles through one content service; the CONTENT_SOURCE variable routes it to static TypeScript files for rollback or to Payload CMS on Neon Postgres, which the admin and agent REST API also write to.

An earlier draft of the plan had a silent runtime fallback: if the database was unreachable, serve the static files. I dropped it from the plan. Once the first CMS-only article is published, the fallback does not have that article, so its URL would return 404 while a cached sitemap still lists it. A silent fallback also hides outages. The final design falls back only at deploy time, and only when a person flips the flag. Pages are statically generated, so a database outage at request time just means the CDN keeps serving the last good render.

Two details changed real output:

  • Pagination. Payload's find returns 10 documents by default. Without pagination: false, 8 of 18 posts would have disappeared from the blog index.
  • Ordering. Category pages had been in raw array order, which mixed dates. Both modes now sort by publishedAt, newest first, with ties in source order, so the two backends produce identical lists. This was an intentional change on 4 category pages and was approved as an expected diff.

Proving zero regressions with a parity diff

"No SEO regressions" is not something you can check by clicking around. The migration gate was a script, scripts/parity-diff.mjs, that crawls every URL in the sitemap plus the machine-readable endpoints and records what a crawler sees on each one:

Proving zero regressions with a parity diff
Captured per pathWhy it matters
HTTP status and redirect locationCatches new 404s and redirect chains
<title>, meta description, robots metaSearch snippets and indexing directives
Canonical URLDuplicate-content signals
Every JSON-LD blockBlogPosting, FAQPage, HowTo, and breadcrumb rich results
Open Graph and Twitter image URLs, plus their HTTP statusSocial previews, at both new and legacy URLs
Visible textSilent content loss
Full body of the sitemap, feed, llms files, and /api/*Feeds and APIs other systems depend on

Snapshots are keyed by path, so production can be compared against a preview deployment or localhost. Values generated fresh on every build (UUIDs, epoch timestamps, HTTP dates) are masked, and 5 tool pages that render a random or clock-based demo skip only their visible text. Their metadata is still compared.

The diff ran at three gates:

  1. Route-group restructure: 142 paths, with only intended differences (the 404 page and the new robots.txt rules).
  2. Static mode vs. CMS mode on the same build: zero differences across 142 paths.
  3. Production cutover, live site, static vs. CMS: zero differences across 142 paths.

A clean parity diff proves the migration did not change what crawlers receive. It does not prove rankings are unaffected, because those depend on things outside the HTML. That is why the cutover plan also included a two-week watch on Search Console coverage, 404 rates, and Core Web Vitals.

Database migrations that cannot hang a deploy

Payload's Postgres adapter can sync the schema in two ways: Drizzle's push, which is on by default in development, and committed migration files. The split I settled on was push for local iteration only, and migrations for every deployed database. A build script runs payload migrate before next build, but only when VERCEL_ENV is production or preview, and each scope has its own Neon Postgres branch.

The hard lesson came from push. A database that has been schema-pushed gets a marker row in payload_migrations (name dev, batch -1). When payload migrate sees that row, it waits for an interactive confirmation. In CI nobody answers, so the build hangs until Vercel's timeout. The marker reached a deployed database twice:

  • The Neon preview branch was created from the dev branch and inherited the marker.
  • A payload run script re-added it, because push runs from any non-production process, not only next dev.

Three changes closed it off:

  1. Push is opt-in. The adapter uses push: process.env.PAYLOAD_DEV_PUSH === "true", and only pnpm dev sets it.
  2. The deploy script checks first. Before migrating, it queries payload_migrations for a batch -1 row and fails immediately with an explanation instead of hanging.
  3. Deployed branches come from production. Create Neon branches for preview and staging from the production branch, never from dev.

Migrations also run before the new code is live, so they stay additive: add columns and tables first, drop them in a later deploy once nothing reads them.

Re-implementing compile-time content rules as validation

The TypeScript types were the site's editorial gate. A tuple type like faq: [FaqItem, FaqItem, ...FaqItem[]] makes the compiler reject a post with fewer than two FAQ entries. A CMS has no compiler, so each rule became a Payload field validation or a beforeChange hook:

Re-implementing compile-time content rules as validation
RulePayload enforcement
Summary is a direct answer40–60 words, hard fail outside that range
Author note is specific to the topicAt least 15 words and unique across all posts and guides
FAQAt least 2 entries, each answer at least 20 words
Citations are never fabricatedAt least 1, absolute https, and the URL must respond when saved
SEO fieldsTitle up to 60 characters, description up to 160, canonical path must match the slug
PublishingBlocked until a reviewer runs a GEO (AI-citation readiness) review and ticks geoReviewed

The citation check issues a HEAD request with a GET fallback and a 5-second timeout. Responses of 401, 403, and 429 count as live, because bot-protected sites return them to scripts. Results are cached for an hour, so re-saving a post does not re-fetch every source.

These rules were stricter than what the compiler had enforced. Before seeding, every existing article was brought into compliance on its own branch: 46 violations across the 30 articles, including 15 SEO titles, 12 descriptions, 10 summaries, 7 author notes, and one dead citation that was replaced. The seed script then ran with validation on and no bypass.

AI agents get their own API-key users with the ai-agent role. Whatever an agent sends, a hook forces the document to an unreviewed draft attributed to that agent, and update and delete are admin-only. Agents are limited to 20 new drafts per hour each, counted in the database so the limit holds across serverless instances.

The cutover sequence

The production database started empty. The order mattered more than any single step:

Diagram of the six-step production cutover: migrate the empty database, create the admin offline, seed 30 articles with validation, deploy still static, flip CONTENT_SOURCE to cms with a parity diff of 0 differences across 142 paths, then test the agent-to-publish workflow.
  1. Migrate the empty production branch from a local checkout: 3 migrations.
  2. Create the first admin user from a script before deploying. Payload shows an open "create first user" screen while the users collection is empty. Bootstrapping offline means that screen is never reachable on the live site.
  3. Dry-run the seed, which prints the target host and the plan, then seed for real: 30 articles created, 0 failures, each one read back and deep-compared to its source entry. Production writes require --confirm-host to match the database host.
  4. Deploy 1, still static. Smoke-test: /admin redirects to login, the first-user screen redirects away, /cms-api/users returns 403, GraphQL returns 404, public /api/* routes return 200.
  5. Deploy 2, same commit, `CONTENT_SOURCE=cms`. Run the parity diff against the live site: zero differences across 142 paths.
  6. Exercise the real workflow. An agent submitted a draft over the REST API, it was reviewed and published from /admin, and it appeared on its page, the blog index, the sitemap, the feed, the llms files, and the search index.

Rollback at every point after step 5 is one environment variable and a redeploy. That works only while the static files stay current, which is the main reason to delete them on a schedule instead of leaving them to drift.

What it bought and what it cost

Some of the gains were planned and some were side effects:

  • Publishing takes seconds, not a build. A save invalidates the whole frontend route group plus the sitemap, feed, llms files, and search index, and pages regenerate on their next request. I invalidate everything instead of keeping a list of affected paths, because article data appears on too many pages for a hand-written list to stay correct.
  • Less client JavaScript. The search palette used to bundle every article into client code. It now fetches a static /search-index.json the first time it opens. Bytes downloaded dropped 59% on the homepage, 70% on a blog post, and 62% on the tools index.
  • Safe agent submissions. An agent's draft is one authenticated POST, and it cannot publish, edit, or delete anything.
  • Scheduling and renames. Scheduled publishing runs from a Vercel Cron job every 5 minutes. Renaming a published slug creates a 301 automatically and re-points older redirects so they never chain.

The costs are real too. Content rules moved from compile time to runtime, so a broken rule now surfaces when someone saves, not when the build runs. The site gained a database to migrate and back up, a larger dependency tree, longer builds, and one more system to monitor. For a single-author site without an AI drafting pipeline, I would still recommend the GitHub-PR option over this one.

A checklist for your own migration

  • Write down the alternatives and the condition under which you would undo the decision.
  • Put every content read behind one service and one flag, then ship that swap before the cutover.
  • Avoid silent runtime fallbacks. Make rollback a deliberate, deploy-time action.
  • Build a parity crawler that diffs titles, canonicals, JSON-LD, social images, feeds, and visible text, and require zero unexplained differences.
  • Watch for Payload's default limit of 10 documents in every list query.
  • Keep schema push off for anything that deploys, and fail fast on a pushed database.
  • Re-implement every compile-time content rule as validation, and fix existing content before seeding instead of bypassing the rules.
  • Bootstrap the first admin offline so the setup screen is never public.
  • Keep the old source current until the rollback window closes, then delete it.