Skip to main content
Cloud Architecture & DevSecOps
11 min read

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.

AY
Artur Yusupov
Fullstack Web Engineer & AI Developer
Migrating Next.js 16 from Vercel to Cloudflare Workers: $0/Month Unlimited Static Assets, 1.22ms Hybrid RAG & DevSecOps

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:

1
Account-Wide Hard Bandwidth Cutoff: The Hobby tier enforces a shared 10 GB Fast Origin Transfer quota across every project in the team.
2
Noisy Neighbor Failure: One unrelated sibling project with uncached SSR and broad middleware burned 20.84 GB (over 28,000 middleware invocations in 12 hours), triggering an immediate 30-day pause of the entire team.
3
Collateral Downtime: Our healthy portfolio site had consumed just 8.38 MB and 291 requests in 12 hours, yet returned HTTP 503/402 across all 520 SEO-indexed pages.

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
Static Bandwidth & Requests
Old Setup (Shared Serverless Hobby)
10 GB/mo Fast Origin Transfer cap (hard team pause)
New Setup (Cloudflare Workers + Static Assets)
Unlimited & Free (Static Assets bypass Worker)
Dimension
Static Asset Capacity
Old Setup (Shared Serverless Hobby)
Shared deployment storage limits
New Setup (Cloudflare Workers + Static Assets)
20,000 files (5,751 used), up to 25 MiB per file
Dimension
Dynamic API Quota (`/api/chat`)
Old Setup (Shared Serverless Hobby)
Metered functions + middleware invocations
New Setup (Cloudflare Workers + Static Assets)
100,000 Worker invocations/day (resets daily 00:00 UTC)
Dimension
Worker CPU Time (Measured)
Old Setup (Shared Serverless Hobby)
Cold-start Node runtime
New Setup (Cloudflare Workers + Static Assets)
1.22 ms median (10 ms Free limit, ~8x margin)
Dimension
Build Pipeline Quota
Old Setup (Shared Serverless Hobby)
Shared queue
New Setup (Cloudflare Workers + Static Assets)
3,000 build minutes/mo (~1.5 min/deploy = ~2,000 deploys/mo)
Dimension
Monthly Infrastructure Cost
Old Setup (Shared Serverless Hobby)
$0 (with 30-day outage risk) or $20+/seat
New Setup (Cloudflare Workers + Static Assets)
$0/month

How Traffic Splits at the Edge

In wrangler.jsonc, one single setting unlocks unlimited static delivery:

JSON
{
  "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 with 405, syncs encrypted Worker Secrets into process.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:

1
Primary Production (Cloudflare Workers Builds -> `www.yusupovartur.com`):
  • Runs pnpm run build:cf (scripts/build-cf-workers.mjs):
1
Generates the prebuilt inverted BM25 RAG index (node scripts/generate-rag-index.mjs).
2
Temporarily parks app/api and proxy.ts (restored in finally + SIGINT/SIGTERM traps) because Next.js output: 'export' rejects force-dynamic routes.
3
Executes CF_STATIC_EXPORT=1 next build to emit all 520 static pages into ./out.
4
Verifies all 13 critical output artifacts (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).
2
Secondary SPA Mirror & DevSecOps Gate (GitHub Actions -> `gh-pages`):
  • 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) and pnpm 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 the gh-pages fallback 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:

1
Runtime Index Construction (~380 ms on cold start): On the first /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.
2
Dead Markdown Weight (3.4 MB in Worker bundle): Importing 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.
3
Regex Compilation Storm (~52 ms on unmatched queries): 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.mjs precomputes all 340 chunks, 17,293 indexed tokens as flat interleaved [docIdx, tf, ...] posting arrays, pre-folded titles/technologies, and lightweight blogSummaries (stripping ~3.4 MB of raw Markdown from the Worker).
  • Zero-Allocation Scoring & Fuzzy Search: retrieveKnowledge() scores only matched postings into Float64Array accumulators; damerauLevenshteinDistance() reuses 3 module-level Int32Array scratch buffers; PROJECT_BY_SLUG uses O(1) Map lookups with bounded query memoization.
  • Fast-Path FAQ Matching: matchesFaqKeyword() short-circuits 99.5% of non-matches with lower.indexOf(lowerKw) === -1 before touching a cached RegExp.
  • Lazy OpenAI SDK Loading: @ai-sdk/openai, ai, and zod tools load dynamically only when OPENAI_API_KEY is configured, and unused LLM prompt assembly is skipped in $0/mo local RAG mode.

Verified Production Metrics on Cloudflare Edge

Metric
Worker CPU Time (Cloudflare Edge)
Before Optimization
206 ms peak
After Optimization
`1.22 ms` median
Improvement
~168x faster
Metric
Wall Time (Cloudflare Edge)
Before Optimization
215 ms
After Optimization
`11 ms`
Improvement
~19.5x faster
Metric
Memory Usage (Isolate)
Before Optimization
34 MB peak
After Optimization
`17.93 MB` P50 / `24.63 MB` P90
Improvement
Well inside 128 MB cap
Metric
Worker Errors
Before Optimization
0 (burst-dependent)
After Optimization
`0` (deterministic <10ms)
Improvement
Production-safe on Free

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, and Cross-Origin-Opener-Policy: same-origin. API responses additionally enforce Cache-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/DMARC via Cloudflare Email Routing + Brevo), self-hosted GDPR variable fonts (@fontsource-variable), and HMAC-SHA256 rate limiting (15 req/hour) keyed on cf-connecting-ip with an encrypted RATE_LIMIT_SALT Worker 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:live post-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=estimator deep links survive intact.
  • Permanent 308 redirects in public/_redirects for / -> /en and legacy slugs across all 4 locales.
  • Verified Indexing & GEO:
  • Google Search Console verified 512 URLs in sitemap.xml on 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.

Battle-Tested Production Proof

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:

Architecture Consulting

Planning a tech stack migration or new build?

Discuss architectural requirements with my interactive RAG AI assistant or connect directly for an engineering assessment.