林允中 Lîm, Ún-tiong

基礎設施筆記

From Next.js to Astro: Pitfalls and Epiphanies of a Cloudflare Workers Deployment

· --

From Next.js to Astro: Pitfalls and Epiphanies of a Cloudflare Workers Deployment

Why Not Vercel

I was building a personal website, lzong.tw. Sanity CMS + a frontend framework, deployed to the cloud. Vercel is Next.js's birthplace — zero-config deployment. But I chose Cloudflare Workers.

The reason is simple: Cloudflare's free tier is generous, the CDN is fast, and I already had my DNS on Cloudflare. Workers Builds (GA April 2025) provides the same git-connected push-to-deploy experience as Vercel. Cloudflare Pages is deprecated — Workers is the only frontend deployment option now.

Sounds great.

The First Architecture: Next.js + OpenNext

Next.js can't run directly on Cloudflare Workers — it requires a Node.js server. @opennextjs/cloudflare is a translation layer that converts Next.js's server code into a format Workers can execute.

Unknown block type "code", specify a component for it in the `components.types` option

Four layers. Each one is a potential breaking point.

What happened next proved just how fragile this path was.

21 Pitfalls

I've categorized every pitfall I hit into six groups. Each one was genuinely encountered and took real time to fix.

Build Pipeline Pitfalls

1. Build script infinite recursion — Setting build in package.json to npx @opennextjs/cloudflare build, but OpenNext internally calls npm run build, creating a loop. build must be next build. Almost nobody mentions this online.

2. pnpm deploy is a reserved command — pnpm reserves deploy for monorepo workspace deployment. Your deploy script needs to be renamed to something like cf:deploy.

3. open-next.config.ts must be fully specified — An empty default: {} throws errors. You must explicitly specify wrapper, converter, proxyExternalRequest, incrementalCache, tagCache, and queue.

4. Cloudflare Dashboard build command isn't in git — Switch frameworks, switch build commands, but the Dashboard settings are manual. Forget to update them and it'll run the old OpenNext command.

Runtime Compatibility Pitfalls

5. @sanity/client crashes on Workers — Under the hood it uses get-it for HTTP requests, and get-it uses Node.js's https.request. OpenNext's unenv polyfill doesn't implement this API.

Unknown block type "code", specify a component for it in the `components.types` option

This was the single most critical issue in the entire process. The fix: bypass @sanity/client entirely and use native fetch to call the Sanity HTTP API directly.

Unknown block type "code", specify a component for it in the `components.types` option

6. fs.readFileSync crashes the entire Worker on startup — OpenNext bundles all server-side code into a single Worker. Any route that has import { readFileSync } from 'fs' will execute at startup, regardless of which route is actually being accessed.

7. @vercel/og doesn't work — It depends on Vercel's edge runtime internals. Alternative: use satori directly (the library underlying @vercel/og).

8. Edge runtime config breaks OpenNext — export const config = { runtime: 'edge' } in API routes conflicts with OpenNext bundling. On Workers everything is edge anyway — just remove it.

9. nodejs_compat_v2 is actually stricter — Switching to it produces No such module "node:fs". Stick with nodejs_compat.

Bundle Size Pitfalls

10. Worker exceeds 3MB free tier limit — When Sanity Studio's sanity package is embedded in Next.js, gzipped size is ~4.7MB. The free tier limit is 3MB.

Fix: extract Studio into a standalone deployment at *.sanity.studio (free). Move Studio-only packages to devDependencies, bringing the Worker down to ~1.8MB.

Routing Pitfalls

11. Next.js built-in i18n doesn't work — The i18n config in next.config.ts requires a Node.js server for locale negotiation. Switch to middleware + [lang] dynamic routes instead.

12. getStaticProps can't return a redirect during prerender — Use middleware redirect + client-side fallback for the root route.

Toolchain Pitfalls

13. wrangler.jsonc name must match Dashboard — Config says lzong-tw, Dashboard project is lzong-tw-sanity — deployment fails outright.

14. Sanity CLI doesn't recognize Next.js path aliases — sanity deploy uses Vite build and doesn't read tsconfig.json's baseUrl. You need to manually add Vite aliases in sanity.cli.ts.

15. sanity deploy build output should be gitignored — dist/ and .sanity/ can get accidentally committed.

16. sanity deploy crashes on assertValue() — The standalone Studio doesn't have .env.local, so projectId/dataset must use hardcoded fallbacks.

17. sanity deploy requires remembering hostname and appId — Otherwise you have to interactively select them every time.

Debugging Pitfalls

18. Wrangler observability must be manually enabled — Add "observability": { "enabled": true } to wrangler.jsonc to get runtime logs.

19. 500 errors require wrangler tail — Build logs only capture build-phase errors. Runtime errors need wrangler tail or Dashboard real-time logs.

Frontend Pitfalls

20. Tailwind `container` class has padding asymmetry — At certain viewport widths, left and right margins are unequal. Replace with max-w-6xl mx-auto px-6 md:px-12.

21. Dark mode anti-flash — The <html> class must be set before HTML parsing begins, otherwise it renders light mode first then flashes to dark mode. Fix with an inline script in <head>.

Easy-to-Overlook Pitfalls

22. Tailwind v4 + Astro requires @tailwindcss/vite — The @astrojs/tailwind integration only supports Tailwind v3. For v4, use @tailwindcss/vite as a Vite plugin instead of the integration.

23. Cloudflare Dashboard settings aren't in git — Build command, deploy command, environment variables are all manually configured in Dashboard. After switching frameworks, forgetting to update the build command means CI still runs the old npx @opennextjs/cloudflare build. Always record the correct Dashboard settings in CLAUDE.md or README.

The Turning Point: Version Hell

All 23 pitfalls fixed. Site is live. Then the Sanity Dashboard says: please upgrade to v5.

After upgrading to Sanity 5, @sanity/visual-editing and next-sanity require Next.js 16. After upgrading to Next.js 16:

Unknown block type "code", specify a component for it in the `components.types` option

OpenNext 1.17.1 doesn't support Next.js 16. Its peer dependencies claim support for ^16.1.5, but it crashes at runtime.

Downgrade to Next.js 15? The latest Sanity packages require Next 16. Downgrade to Sanity 4? The Dashboard nags you to upgrade to 5.

Unknown block type "code", specify a component for it in the `components.types` option

Three-way deadlock. No solution.

The Epiphany

Looking back at those 21 pitfalls, they share a common root cause:

Unknown block type "code", specify a component for it in the `components.types` option

OpenNext is a translation layer. It translates Next.js's Node.js server behavior into Workers' edge runtime behavior. Every "pitfall" is a translation fidelity loss:

  • https.request not implemented -- translation layer missing polyfill
  • fs.readFileSync crash -- translation layer's bundling approach is wrong
  • edge runtime config conflict -- translation layer's conceptual model differs from Next.js
  • Next.js 16 incompatibility -- translation layer can't keep up with upstream breaking changes

The problem isn't any individual pitfall — it's the translation layer itself.

A 30-Minute Migration

Astro has a native Cloudflare Workers adapter (@astrojs/cloudflare). No translation layer needed.

Unknown block type "code", specify a component for it in the `components.types` option

Two fewer layers. I used three parallel agents for the migration:

| Agent | Responsibility | Time |

|-------|---------------|------|

| A | Homepage + all Astro components + React island (dark mode toggle) | ~3 min |

| B | Post pages + Portable Text rendering + all sub-components | ~4 min |

| C | RSS + Sitemap + OG image endpoint + middleware + config cleanup | ~4 min |

73 files changed. Deleted 6,897 lines of Next.js code, added 3,394 lines of Astro code.

Results:

| | Next.js + OpenNext | Astro |

|---|---|---|

| Bundle size | 4.7MB gzip (over limit) | 1.8MB gzip |

| Translation layer | OpenNext (third-party) | None (native adapter) |

| Workers 500 errors | Yes, multiple times | None |

| Version conflicts | Next 15/16 vs Sanity vs OpenNext | None |

| Deploy success | After N attempts | First try |

All OpenNext-related problems from the 21 pitfalls (#1, #3, #5-10) simply vanished. They weren't fixed — they ceased to exist.

Post-Astro Pitfalls

Thought switching frameworks would be the end? Nope. Four more pitfalls after migration:

24. satori's yoga-wasm is blocked by Workers — OG image generation uses satori (renders JSX to SVG), but satori depends on yoga-wasm under the hood. Workers prohibit WASM instantiation: Wasm code generation disallowed by embedder. Fix: abandon satori entirely, use a pure SVG string template.

25. Cascading effects of framework migration — After deleting Next.js's components/ directory, Sanity Studio plugins were still importing from it. OpenGraphPreview imports components/OpenGraphImage, AuthorAvatarPreviewPane imports components/AuthorAvatar, OpenGraphInput imports constants from components/OpenGraphImage. Each one had to be found and inlined or rewritten.

26. Leftover dependencies from the old framework — sanity.cli.ts used @next/env to load .env.local, but that package was removed during migration. Had to switch to dotenv. sanity.config.ts had presentationTool and previewDocumentNode that depended on Next.js's preview mode API route — also had to be removed.

27. Astro API endpoints don't support `.tsx` — Assumed renaming .ts to .tsx would enable JSX, but Astro's endpoint routing only recognizes .ts. .tsx returns 404. This is why the OG image ultimately used an SVG string template instead of JSX.

These four pitfalls share a common lesson: Framework migration isn't just deleting old files and creating new ones. Every dependency on your old framework — packages, CMS plugins, CLI config, API patterns — will surface when you think you're done.

Pitfalls Discovered After Stabilization

The site was live and functional. Then I ran 7 rounds of automated review with Codex CLI, and found more:

28. SEO meta was almost entirely missing — After the Astro migration, nobody added og:title, og:url, canonical, hreflang, twitter:card, or robots.txt. The homepage didn't even have <meta description>. Framework migration ensures "it works," not "it can be found."

29. Nine `"latest"` versions in package.json — Nine Sanity packages used "latest". Every pnpm install produced different results; CI was non-reproducible. Rule: always pin versions.

30. OG image SVG: wrap first, escape second — If you escapeXml() before wrapText(), entities like &amp; can get split across <tspan> elements, producing invalid SVG. Correct order: wrap the raw text into lines, then escape each line individually.

31. `strictNullChecks: false` + missing `env.d.ts` — TypeScript configuration degradation from the migration. strictNullChecks was disabled, and src/env.d.ts (Astro's type declarations) was never created. Six type errors disappeared silently. A single /// <reference types="astro/client" /> line fixed all of them.

32. Sanity slugs must be globally unique — Sanity's slug validation doesn't scope by language field. zh-Hant and en versions of the same post cannot share a slug. Solution: English versions use a -en suffix.

33. `npx tsx` doesn't load `.env.local` — Sanity CLI auto-loads it via dotenv, but standalone scripts don't. You need import { config } from 'dotenv'; config({ path: '.env.local' }) explicitly.

34. Windows CRLF breaks frontmatter regex — ^---\n doesn't match \r\n on Windows. Frontmatter parsing fails silently, all fields fall back to defaults. Always use \r?\n in regex that parses Markdown frontmatter.

35. Sanity `client.create()` without `_id` publishes immediately — I assumed create() would produce a draft. It doesn't — Sanity auto-generates an ID without the drafts. prefix, which means the document is published instantly. To create actual drafts, use createOrReplace() with a drafts.-prefixed ID.

36. `npx sanity documents delete` doesn't delete `drafts.*` documents — The CLI delete command only targets published documents. Draft-prefixed documents become invisible orphans that cause slug conflicts and Studio errors. You must use the transaction API with perspective: 'raw' to find and delete them.

37. `prerender = true` pages are static — After publishing content in Sanity, the Cloudflare-hosted pages don't update automatically. You must run pnpm cf:deploy to rebuild. There's no webhook, no ISR — it's a full rebuild every time.

What Remains

Let me sort this out. Three categories of pitfalls:

Translation layer pitfalls (vanished after switching to Astro): Build recursion, OpenNext config, edge runtime conflicts, middleware-manifest incompatibility — all gone.

Platform pitfalls (same regardless of framework):

  • Workers has no filesystem — use fetch to load static assets
  • Workers' https.request polyfill is incomplete — use native fetch
  • Workers prohibits WASM instantiation — can't use satori
  • Bundle size limits — Studio must be deployed separately

Migration pitfalls (temporary but annoying):

  • Old framework imports lingering in CMS plugins
  • Old framework dependencies lingering in CLI config
  • Preview mode / visual editing features broken (zero impact for a personal blog)

The core principle remains: Cloudflare Workers is neither Node.js nor a browser. It's a third thing — it has `fetch` but no `fs`, V8 but no WASM, Web APIs but incomplete. Write for this platform specifically; don't assume it's something else.

Conclusion

Four lessons.

First, if the adapter is the problem, switch frameworks — don't switch workarounds. I spent hours fixing 21 OpenNext pitfalls, then made them all disappear in 30 minutes by switching frameworks. Sunk cost is real, but the cost of continuing to invest is higher.

Second, fewer translation layers is better. Every layer of translation is a potential source of version conflicts, polyfill gaps, and breaking changes. Sanity -> fetch -> Astro -> Workers has two fewer breaking points than Sanity -> next-sanity -> Next.js -> OpenNext -> Workers.

Third, platform constraints don't disappear when you switch frameworks. Workers doesn't support WASM, doesn't support fs, doesn't support https.request — none of this has anything to do with which framework you use. Switching frameworks solves translation layer problems, not platform problems. Know which pitfalls belong to which layer so you know what to fix.

Fourth, a successful build doesn't mean it runs. The most painful bugs only appear at runtime. https.request is not implemented, Wasm code generation disallowed — these don't show up in build logs. Always enable observability + wrangler tail, and verify immediately after deployment.

This article documents the state of things as of March 2026. OpenNext may fix Next.js 16 compatibility in future versions, and Workers may lift WASM restrictions. But "fewer translation layers is better" and "know which layer owns the problem" are principles that won't expire.


--

Comments