Migrating Next.js 16 from Vercel to Cloudflare Workers: $0/Month Unlimited Static Assets, 1.22ms Hybrid RAG & DevSecOps
Why we moved a 520-page 4-locale Next.js 16 platform and autonomous Hybrid RAG API off a shared 10 GB serverless origin cap onto Cloudflare Workers + Static Assets, cutting Edge CPU from 206ms to 1.22ms with dual CI/CD, full HTTP security headers, and zero SEO/GEO regressions.
1. Why We Dropped Our Previous Hosting Model
For over a year, our Next.js 16 portfolio platform (520 localized routes across English, Ukrainian, Spanish, and German, 71 case studies, 47 engineering articles, and an autonomous Hybrid RAG AI assistant) ran on a shared Vercel Hobby team account.
On paper, that setup looked effortless: push to master, get automatic builds, edge caching, and serverless API routes. In practice, it hid a structural blast-radius flaw:
The engineering lesson was unambiguous: never serve static HTML, WebP/PNG media, sitemaps, and RSS feeds behind a metered serverless origin quota, and never couple a mission-critical personal brand or B2B storefront to a shared blast radius.
2. Why We Chose Cloudflare Workers + Static Assets ($0/Month)
Rather than paying for metered bandwidth or spinning up duplicate hobby accounts (which violates platform fair-use rules), we redesigned the deployment around a Static-First Hybrid Edge model on Cloudflare Workers + Static Assets:
| Dimension | Old Setup (Shared Serverless Hobby) | New Setup (Cloudflare Workers + Static Assets) |
|---|---|---|
| Static Bandwidth & Requests | 10 GB/mo Fast Origin Transfer cap (hard team pause) | Unlimited & Free (Static Assets bypass Worker) |
| Static Asset Capacity | Shared deployment storage limits | 20,000 files (5,751 used), up to 25 MiB per file |
| Dynamic API Quota (`/api/chat`) | Metered functions + middleware invocations | 100,000 Worker invocations/day (resets daily 00:00 UTC) |
| Worker CPU Time (Measured) | Cold-start Node runtime | 1.22 ms median (10 ms Free limit, ~8x margin) |
| Build Pipeline Quota | Shared queue | 3,000 build minutes/mo (~1.5 min/deploy = ~2,000 deploys/mo) |
| Monthly Infrastructure Cost | $0 (with 30-day outage risk) or $20+/seat | $0/month |
How Traffic Splits at the Edge
In wrangler.jsonc, one single setting unlocks unlimited static delivery:
{
"name": "yusupovartur-portfolio",
"main": "worker/index.ts",
"compatibility_date": "2026-11-24",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"directory": "./out",
"binding": "ASSETS",
"html_handling": "drop-trailing-slash",
"not_found_handling": "404-page",
"run_worker_first": ["/api/*"]
}
}Because run_worker_first matches only /api/*:
- 99.5%+ of requests (all 520 HTML pages, JS/CSS chunks, WebP/PNG images,
sitemap.xml,feed.xml,llms.txt) are served directly by Cloudflare Static Assets with 0 Worker invocations. - Only `POST /api/chat` wakes the V8 isolate in
worker/index.ts, which rejects non-POST methods with405, syncs encrypted Worker Secrets intoprocess.env, and invokes our Next.js route handler.
3. Dual CI/CD Architecture & Automated Build Pipeline
Every git push origin master triggers two independent pipelines:
- Runs
pnpm run build:cf(scripts/build-cf-workers.mjs):
node scripts/generate-rag-index.mjs).app/api and proxy.ts (restored in finally + SIGINT/SIGTERM traps) because Next.js output: 'export' rejects force-dynamic routes.CF_STATIC_EXPORT=1 next build to emit all 520 static pages into ./out.en/ua/es/de.html, 404.html, sitemap.xml, robots.txt, feed.xml, llms.txt, llms-full.txt, IndexNow key, _headers, _redirects).- Runs
npx wrangler deploy(~1m 35s total build + deploy time).
- Runs a strict 9-stage verification pipeline on Node.js 24 LTS +
pnpm --frozen-lockfile: - Gitleaks secret scan (SHA-256 verified binary)
- SAST:
pnpm exec tsc --noEmit(strict zero-any) andpnpm lint - TDD:
pnpm test(44 Vitest suites, 249 specs) - SCA:
pnpm audit --prod --audit-level=high - Vite Production Build + Contact Leak Scan:
pnpm build+node scripts/check-contact-leak.mjs(verifies zero plaintext email/phone strings in built HTML/JS) - A11y & CWV: Playwright E2E + axe-core WCAG 2.2 AA / EAA 2026 + Lighthouse CI
- Only when all 9 gates pass does GitHub Actions publish
dist/to thegh-pagesfallback mirror.
4. The Hidden Trap We Hit & Solved: Cutting Edge CPU from 206ms to 1.22ms
The migration worked immediately - until we inspected Cloudflare Analytics and spotted `CPU time P90: 206 ms`.
Cloudflare Workers Free enforces a 10 ms CPU time limit per invocation. Although Cloudflare occasionally allows cold-start bursts when host capacity is spare (so errors were still 0), running at 206 ms is a ticking Error 1102 time bomb under real traffic.
Profiling the exact bundled Worker locally revealed three hidden CPU killers:
/api/chat request, knowledge.ts built 340 multilingual chunks, ran Markdown heading regexes over 188 full 4-language articles, and tokenized megabytes of text into BM25 maps.allBlogPosts pulled 47 full long-form Markdown bodies into the Worker bundle even though /api/chat only ever uses titles, descriptions, TL;DRs, and slugs.matchesFaqKeyword() compiled 150+ Unicode new RegExp(..., 'iu') objects with \p{L}\p{N} on the fly during every unmatched query, while resolveProjectFromQuery() ran up to 25 redundant times per request.The Engineering Fix
- Build-Time Inverted BM25 Index:
scripts/generate-rag-index.mjsprecomputes all 340 chunks, 17,293 indexed tokens as flat interleaved[docIdx, tf, ...]posting arrays, pre-folded titles/technologies, and lightweightblogSummaries(stripping ~3.4 MB of raw Markdown from the Worker). - Zero-Allocation Scoring & Fuzzy Search:
retrieveKnowledge()scores only matched postings intoFloat64Arrayaccumulators;damerauLevenshteinDistance()reuses 3 module-levelInt32Arrayscratch buffers;PROJECT_BY_SLUGuses O(1)Maplookups with bounded query memoization. - Fast-Path FAQ Matching:
matchesFaqKeyword()short-circuits 99.5% of non-matches withlower.indexOf(lowerKw) === -1before touching a cachedRegExp. - Lazy OpenAI SDK Loading:
@ai-sdk/openai,ai, andzodtools load dynamically only whenOPENAI_API_KEYis configured, and unused LLM prompt assembly is skipped in$0/molocal RAG mode.
Verified Production Metrics on Cloudflare Edge
| Metric | Before Optimization | After Optimization | Improvement |
|---|---|---|---|
| Worker CPU Time (Cloudflare Edge) | 206 ms peak | `1.22 ms` median | ~168x faster |
| Wall Time (Cloudflare Edge) | 215 ms | `11 ms` | ~19.5x faster |
| Memory Usage (Isolate) | 34 MB peak | `17.93 MB` P50 / `24.63 MB` P90 | Well inside 128 MB cap |
| Worker Errors | 0 (burst-dependent) | `0` (deterministic <10ms) | Production-safe on Free |
206 ms peak215 ms34 MB peak0 (burst-dependent)5. DevSecOps, SEO & GEO Parity at the Edge
Moving off Vercel meant we could no longer rely on vercel.json or Next.js runtime middleware for headers and redirects. We achieved 100% parity natively in Cloudflare:
- HTTP Security Headers (`public/_headers` + `worker/index.ts`): Every static page and API response emits
Strict-Transport-Security,Content-Security-Policy,X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: strict-origin-when-cross-origin,Permissions-Policy, andCross-Origin-Opener-Policy: same-origin. API responses additionally enforceCache-Control: no-store, max-age=0. - Transport & WAF Hardening:
SSL/TLS Full(TLS 1.3), Always Use HTTPS enabled, Bot Fight Mode enabled, Cloudflare Managed Ruleset active, authenticated DNS email records (SPF/DKIM/DMARCvia Cloudflare Email Routing + Brevo), self-hosted GDPR variable fonts (@fontsource-variable), and HMAC-SHA256 rate limiting (15 req/hour) keyed oncf-connecting-ipwith an encryptedRATE_LIMIT_SALTWorker Secret. - 24/7 SRE Observability (UptimeRobot + Cloudflare Observability): External synthetic HTTP/HTTPS monitoring via UptimeRobot guarantees instant outage alerts independent of hosting provider dashboards (the exact layer that catches silent account-level pauses), complemented by Cloudflare Workers Observability (live CPU/RAM/error telemetry), GitHub Dependabot, and
pnpm verify:livepost-deploy header smoke checks. - Canonical SEO Redirects:
- Zone-level 301 Redirect Rule (
https://yusupovartur.com/*->https://www.yusupovartur.com/${1}) with Preserve query string enabled so UTM tags and?chat=estimatordeep links survive intact. - Permanent 308 redirects in
public/_redirectsfor/->/enand legacy slugs across all 4 locales. - Verified Indexing & GEO:
- Google Search Console verified 512 URLs in
sitemap.xmlon day one. - IndexNow accepted 513 URLs (
HTTP 200) immediately after cutover. /feed.xml,/llms.txt,/llms-full.txt, and 1200x630 PNG blog OG images remain 100% static and instant. AI Labyrinth is intentionally disabled so legitimate AI search crawlers are never trapped.
6. Honest Trade-Offs: When NOT to Use This Architecture
No architecture is universal. You should not use Next.js static export + thin Cloudflare Worker if your app requires:
- Per-request dynamic SSR personalized by session cookies across hundreds of routes (use OpenNext on Cloudflare Workers or a containerized Node server instead).
- Heavy server-side CPU workloads (>10 ms) on the Free tier without upgrading to Workers Paid ($5/month for 30,000 ms CPU).
However, for B2B platforms, engineering blogs, portfolios, documentation portals, and marketing sites with a handful of targeted API routes, combining Next.js 16 Static Export + Cloudflare Static Assets + Prebuilt Edge RAG gives you sub-2ms compute, unlimited bandwidth, strict DevSecOps compliance, and $0/month predictable operations.
Where This Architecture is Deployed in Production
These architectural patterns are not abstract theory - they are fully deployed and benchmarked in these live production builds:
Planning a tech stack migration or new build?
Discuss architectural requirements with my interactive RAG AI assistant or connect directly for an engineering assessment.
Related Engineering Articles
Next.js 16 vs Headless WordPress vs Custom PHP: Objective TCO, Performance & SEO Analysis (2026)
An engineering breakdown comparing architecture, maintenance overhead, Total Cost of Ownership (TCO), and Google Core Web Vitals across Next.js 16, Headless WordPress, and custom PHP.
Fullstack AI Lab Architecture Deep-Dive: Compiling 1,135+ MDX Lessons in 90 Seconds with Next.js 16 & Rust MDX-RS
Complete executive and technical breakdown of the Fullstack AI Lab interactive engineering platform: how we cut SSG build times by 14x (from 21.6m to 1.5m), engineered an in-browser WebAssembly WordPress sandbox, an AI Technical Interview Engine, interactive runtime simulators, and a zero-metaphor NotebookLM audio engine.