Troubleshooting
readyFast fixes for the most common build, Cloudflare API, DNS, SSH, runtime, and Agent Trace issues encountered when deploying Next.js apps with NextDeploy.
Source reference: cli/internal/serverless/, shared/nextcompile/, cli/internal/dns/guide.go, shared/agenttrace/
Cloudflare Deploy Issues
Error: KV PUT failed: 429 Too Many Requests (checkRateLimit)
If your deployed Cloudflare Worker throws a 500 Internal Server Error with:
Error: KV PUT failed: 429 Too Many Requests
at async checkRateLimit (worker.mjs:...)
at async runGuard (worker.mjs:...)
- Cause: Cloudflare Workers KV enforces a hard limit of 1
PUTper second to the same key (plus 1,000PUTs/day on the Free plan). Navigating Next.js pages fires both the document request and concurrent<Link>RSC prefetches within the same second, hitting the samerl:<ip>:<windowId>rate-limit key. - Fix 1 — Scope rate limiting away from static/docs routes: Exclude marketing and documentation routes in
nextdeploy.ymland targetrate_limit.pathsto sensitive routes:serverless: cloudflare: protection: enabled: true public_paths: ["/", "/login", "/docs", "/docs/*"] rate_limit: kv_binding: RATE_LIMIT requests_per_minute: 60 paths: ["/api/*", "/app/*"] - Fix 2 — Upgrade/rebuild the NextDeploy binary: Current builds of
shared/nextcompile/runtime_src/guard.mjscoalescekv.putwrites to at most once every1,100msper key per isolate, run writes throughctx.waitUntil(...), and catch KV429errors gracefully so traffic never 500s. Rebuild yournextdeployCLI binary (nextdeploy updateorgo build) and re-runnextdeploy ship.
Next.js 16.4+ Worker 500: TypeError: l2 is not a function / Cannot set property setImmediate
If every route (/, /docs, /api/health) returns HTTP 500 Internal Server Error after upgrading to Next.js 16.4+ and live Cloudflare logs (nextdeploy logs) or local smoke tests show either:
TypeError: l2 is not a function
at r0.loadManifests (...)
or:
Error: Failed to load external module next/dist/compiled/next-server/app-page-turbo.runtime.prod.js:
TypeError: Cannot set property setImmediate of #<Object> which has only a getter
- Cause:
- Next.js
16.4+importsevalManifestFromRelativePath(and relies onhandleMissingreturningundefined) fromnext/dist/server/load-manifest.external.js. Older Worker shims only exportedevalManifestandloadManifestFromRelativePath. - Next.js
16.4+executesinstall()at module load insidenext/dist/server/node-environment-extensions/fast-set-immediate.external.js, assigningrequire("node:timers").setImmediate = patchedSetImmediate, which throws on esbuild's read-only ESM namespace wrapper in Cloudflare Workers.
- Next.js
- Fix: Update/rebuild the
nextdeployCLI binary (nextdeploy updateorgo build -o ./bin/nextdeploy ./cli) socli/internal/serverless/cloudflare/adapter/adapter.goandshared/nextcompile/runtime_src/next_shims/fast_set_immediate.mjsinclude the updatedload-manifest.external.jsandfast-set-immediate.external.jsshims, then re-runnextdeploy ship.
Error: Failed to load external module node:process: Dynamic require of "node:process" is not supported
If markdown/MDX routes or Next.js 16 RSC /_tree segment prefetches (GET /docs/...?_rsc=...) return HTTP 500 with:
Error: Failed to load external module node:process: Error: Dynamic require of "node:process" is not supported
at Context.externalRequire [as x] (worker.mjs:...)
- Cause: Older adapter builds did not include
"process"innativeNodeModules, causing esbuild to leaverequire("node:process")(used by libraries likevfile) external and emit ESM__require("node:process"), which throws at runtime inworkerd. - Fix: Update/rebuild the
nextdeployCLI binary (nextdeploy updateorgo build -o ./bin/nextdeploy ./cli) —adapter.gonow mapsnode:processnatively and enforces a defense-in-depth fallback so unlistedrequire("node:...")calls never emit__require("node:...")— and re-runnextdeploy ship.
native Node addon "*.node" cannot run on Cloudflare Workers
- Cause: A dependency imported a compiled C++
.nodebinary addon (for example nativebcrypt,better-sqlite3, or a native image/crypto binding), which Cloudflareworkerdcannot execute. NextDeploy rejects genuine.nodebinaries on disk during bundling instead of uploading a broken Worker. - Fix: Replace the package with a pure JS / WebAssembly / Web Crypto alternative (e.g.
bcryptjsor Web CryptoSubtleCrypto, Cloudflare D1/Hyperdrive instead of native SQLite), or move the workload behind an external HTTP service.
Inspecting .nextdeploy-cf/_nextdeploy/compat-report.json
Every Worker compile writes <standalone>/.nextdeploy-cf/_nextdeploy/compat-report.json with the exact bundle SHA-256, raw/gzipped sizes, native vs. partial Node built-ins, any stubbed_app_modules (non-framework code importing unsupported built-ins), trimmed packages, and Free/Paid tier warnings. Check this file first when diagnosing unexpected runtime stubs or bundle bloat.
purge_cache: 401 Unauthorized (non-fatal)
Your deployment succeeded, but your Cloudflare API token is missing the Zone → Cache Purge: Purge permission. Add that permission in the Cloudflare dashboard to enable automatic edge cache purges.
duplicate Worker binding name
An .env or Doppler secret key has the same name as a declared Cloudflare binding (e.g. ASSETS, DB, RATE_LIMIT). Rename the binding or remove the conflicting key from .env.
script size exceeds 10MB limit (Worker Script Limit Exceeded)
Cloudflare enforces a 10MB compressed script size limit on the Paid Plan (3MB on Free). While NextDeploy automatically strips .next/static and public/ into R2, extremely large Node.js server dependencies can inflate the worker bundle.
- Fix 1: Externalize heavy server dependencies: In
nextdeploy.yml:serverless: cloudflare: bundle: external: - "@aws-sdk/*" - "canvas" - Fix 2: Inspect standalone build output: Check which node modules are bloated inside
.next/standalone/node_modules. Ensure heavy development tools are indevDependenciesrather thandependencies. - Fix 3: Verify asset offload: Ensure
serverless.cloudflare.resources.r2has anassets_bucketconfigured so static media isn't bundled into code.
Forcing or Comparing Worker Engines
If you want to explicitly force the nextserver or legacy engine for debugging:
NEXTDEPLOY_CF_ENGINE=nextserver nextdeploy ship
NEXTDEPLOY_CF_ENGINE=legacy nextdeploy ship
Local Reproduction of a Cloudflare Worker Bundle
Test your compiled Worker locally against Node before uploading:
NEXTDEPLOY_CF_ENGINE=nextserver NEXTDEPLOY_TEST_STANDALONE=/path/to/your-app/.next/standalone \
go test -v ./cli/internal/serverless/cloudflare/adapter -run TestBuildWorkerBundle_RealStandaloneSmoke
Next.js Runtime & Build Errors
DYNAMIC_SERVER_USAGE Error during prerendering
This occurs when a page or component uses dynamic functions (such as cookies(), headers(), or searchParams) without marking the route segment dynamic.
- Fix: Add route segment config at the top of the route file:
Or ensure dynamic functions are wrapped inside aexport const dynamic = 'force-dynamic';<Suspense>boundary if static shell rendering is desired.
NEXT_NOT_FOUND or NEXT_REDIRECT uncaught exception in edge middleware
Next.js handles notFound() and redirect() by throwing internal errors that must be caught by the Next.js runtime.
- Fix: If your custom middleware or route handler wraps downstream calls in
try/catch, ensure you re-throw Next.js internal errors:try { // business logic } catch (error) { if (error && typeof error === 'object' && 'digest' in error) { throw error; // Let Next.js handle NEXT_REDIRECT or NEXT_NOT_FOUND } // log application error }
Cannot find name 'R2Bucket' or 'KVNamespace' during next build
Install @cloudflare/workers-types as a dev dependency (or type bindings as any / minimal interfaces in lib/env.ts) so next build's TypeScript check resolves Cloudflare binding types cleanly:
npm install -D @cloudflare/workers-types
Add to tsconfig.json:
{
"compilerOptions": {
"types": ["@cloudflare/workers-types/2023-07-01"]
}
}
Doppler CLI prints help text instead of running nextdeploy
Include -- before the command so Doppler doesn't parse nextdeploy flags:
doppler run -- nextdeploy ship
AWS Serverless Deploy Issues
504 Gateway Timeout on Lambda Invocations
- Cause: Lambda cold start exceeded CloudFront or API Gateway's 30-second origin response timeout.
- Fix 1: Increase memory allocation in
nextdeploy.yml(memory: 1792or2048). AWS scales CPU linearly with allocated RAM, cutting initialization cold starts by up to 60%. - Fix 2: Check database connection pooling. Ensure your Prisma/Drizzle connection pool allows fast reconnects or uses AWS RDS Proxy.
- Fix 3: Enable NextDeploy Lambda Response Streaming so the HTTP response headers and initial HTML chunk flush immediately to CloudFront.
RequestEntityTooLargeException: Request must be smaller than 6MB
Synchronous Lambda invocations have a strict 6MB payload limit.
- Fix: If uploading large files, generate S3 Presigned URLs using the AWS SDK so browsers upload directly to S3 without passing payloads through Next.js server actions.
ACM validation stuck in "Pending Validation"
If your domain uses Cloudflare DNS in front of AWS CloudFront, make sure the ACM validation CNAME records are set to DNS only (gray cloud), not proxied (orange cloud). Cloudflare proxying alters CNAME resolution and blocks AWS's automated certificate verification.
VPS & SSH Issues
Host key verification failed or Permission denied (publickey)
- Host Key Verification Failed: The VPS host key changed (e.g. server was rebuilt). Update your known hosts file:
ssh-keygen -R <server-ip> - Permission Denied: Verify your SSH identity file matches the configured user:
Ensure permissions on your private key are strict (ssh -i ~/.ssh/id_ed25519 root@<server-ip>chmod 600 ~/.ssh/id_ed25519).
TLS certificate not issuing on VPS (Caddy error)
- Confirm your domain's
Arecord points to the VPS IP (dig example.com A +short). - Verify ports
80and443are open in your server firewall:sudo ufw status sudo ufw allow 80/tcp sudo ufw allow 443/tcp - Inspect Caddy logs:
journalctl -u caddy -n 100 --no-pager
Node.js memory exhaustion (SIGKILL / Exit code 137)
On low-memory VPS instances (1GB RAM), Next.js builds or high traffic spikes can trigger the Linux kernel Out-Of-Memory (OOM) killer.
- Fix 1: Add a Swapfile:
sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile - Fix 2: Set memory limits in
nextdeploy.yml:vps: resources: memory_limit: 1024M
Agent Trace & Handoff Troubleshooting
Checkpoint Corruption or Missing Trace
If an AI coding agent crashed mid-turn or an interrupted Git rebase disrupted .nextdeploy/trace/:
- Check trace health:
nextdeploy trace status - If the index is out of sync, view the latest raw checkpoints directly:
ls -lat .nextdeploy/trace/checkpoints/ cat .nextdeploy/trace/events.jsonl | tail -n 20 - To reset or re-initialize a corrupted active trace session without losing git history:
rm -f .nextdeploy/trace/active_session.json nextdeploy trace checkpoint -m "Manual recovery checkpoint"
Web UI Port Conflict (:4044 already in use)
If port 4044 is occupied by an existing process:
nextdeploy trace ui --port 4055
Or kill the stale process:
lsof -ti :4044 | xargs kill -9
MCP Server Troubleshooting
Cursor or Claude Code reports "MCP server disconnected"
- Verify the
nextdeploy-mcpbinary is compiled and available in yourPATH:which nextdeploy-mcp || go build -o /usr/local/bin/nextdeploy-mcp ./mcp - Verify
nextdeploy-mcpexecutes cleanly onstdio:echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | nextdeploy-mcp - In Cursor or Claude Code MCP settings, ensure
commandpoints to the absolute path ofnextdeploy-mcpandcwdis set to your workspace root directory.