MELLEPRISE MELLEPRISE AI MP Blog
← All articles

vercel serverless function works locally, then fails in production

Pastel comic of a small serverless function traveling from a laptop into a cloud production maze

Your vercel serverless function works on localhost. Then production returns a 404, a 500, a 504, or silence — and the AI insists the code is correct.

The code may be correct for a laptop. Production is different. A deployed Vercel Function runs on Linux, sees only the files bundled with it, cannot treat the filesystem as permanent storage, reads environment variables from project settings, and stops when its configured duration ends. AI often writes a long-running-server mental model. Vercel runs an invocation model.

What the failure usually looks like

  • 404: Vercel did not create a function for that path, the route is outside the expected server entry, or a rewrite points elsewhere.
  • 500: the function started and crashed; runtime logs should show the exception or module-load failure.
  • 504 / FUNCTION_INVOCATION_TIMEOUT: the invocation did not finish in time, often because an upstream call never returned or no response was sent.
  • ECONNRESET / fetch failed: the external service, database, network path, TLS negotiation, or an IP allowlist closed the connection.
  • undefined environment value: the variable exists locally but is not selected for the deployment environment, or the deployment was built before it changed.

Do not ask the AI to “fix the backend” before you know which state you have. That produces a large diff and hides the real one-line cause.

vercel serverless function production click path

  1. Reproduce the exact production failure. Call the deployed URL directly and save the status, body, deployment URL and UTC time.
  2. Confirm the function exists in that deployment. Open the deployment’s Functions view. In a simple Node API, supported files in the root api/ directory become functions; frameworks use their own route conventions. A file in the wrong folder never becomes public.
  3. Check whether the request reaches your code. Add one first-line log, deploy to Preview, and call it. If nothing appears, suspect routing, rewrites, middleware or deployment protection before business logic.
  4. Search runtime logs. In a linked project, run vercel logs --environment production --query 'level:error' --since 1h. For timeouts, query timeout and match your reproduction time.
  5. Verify environment variables by environment. A local .env file is not deployed configuration. Select each variable for Production or Preview as needed, then redeploy; changes do not affect old deployments. Compare vercel env vars.
  6. Remove filesystem assumptions. Production functions do not have a persistent laptop disk. The filesystem is read-only except temporary /tmp space. Move uploads, SQLite files, caches and generated secrets to real storage or a database.
  7. Check bundled files and native dependencies. A template, JSON file or WASM asset can exist in the repo but miss the function bundle. Native packages can compile locally and fail on Vercel’s Linux runtime. Bundle assets explicitly and replace incompatible native packages.
  8. Prove every branch returns a response. A missing return, forgotten error branch or exception before the response leaves the invocation hanging until the duration limit. Error paths need real HTTP responses too.
  9. Measure the upstream dependency. Time the database query, Stripe call, email API or AI provider separately. If it is slow, raising maxDuration only buys time. Compare Vercel logs with the provider’s logs.
  10. Set maxDuration deliberately. In supported Node.js functions, use export const config = { maxDuration: 60 } or the matching pattern in vercel.json. Use the smallest fitting value. Long AI generation, retries and batch work need architecture, not just a bigger number.
  11. Handle async work honestly. For short work after the response, use waitUntil or after() in supported Next.js versions. For retries, waits or long jobs, use a queue, workflow or durable worker. An unawaited promise after res.json() is not reliability.
  12. Check outbound networking and region. Vercel Functions use dynamic outbound IPs by default. If a database or API allowlists fixed addresses, localhost passes while production fails. Place the function region close to the data when latency or resets correlate with distance.
  13. Debug noisy network detail in Preview only. NODE_DEBUG network logs can expose sensitive headers. Use them temporarily in Preview, remove them, then redeploy the clean fix.

The AI-built failure patterns

The AI wrote a server, not a function. An Express server that listens forever can be right on a VPS and wrong as a serverless deployment unit. In exported AI-builder code, first identify whether it is a static frontend, serverless project or long-running server. Compare lovable export code.

The frontend calls a route that was never deployed. AI-generated fetches often assume /api/... exists because it existed in the builder preview. In the export, the backend may sit outside api/ or in a separate service that was never deployed.

The handler answers too early. Webhook-like code often returns 200 and then tries to update a database or call another API. Locally the process stays alive; in a function the execution context can end. Await required work or explicitly schedule it. For payment side effects, compare stripe webhook.

The AI raises maxDuration first. That hides the difference between slow and broken. First measure, then reduce the work, move the work, or increase the limit for a deliberate reason.

Production checklist

  • The failing route is visible in the correct deployment, not only in the repo.
  • Status, UTC time and deployment URL are recorded.
  • Runtime logs show whether the handler started and where it failed.
  • Required environment variables are selected for the right environment and the project was redeployed.
  • No durable state depends on the local filesystem.
  • Runtime files are bundled; native dependencies are Linux-compatible.
  • Every success and error branch returns a response.
  • External calls have timeouts and only safe retries.
  • Required async work is awaited or explicitly scheduled; durable jobs use a real worker pattern.
  • IP allowlists, regions and upstream limits were checked before blaming Vercel.
  • The deployment still passes the wider lovable deploy production checklist.

Once the function boundary is clear, the repair is usually small: move one file, select one environment variable, await one promise, bundle one asset, or time one upstream call. Debug the invocation production actually runs, not the server your laptop accidentally provided.

FAQ

Why does my vercel serverless function work locally but fail after deployment?

The deployed function runs in a different Linux environment. It has only the bundled files, a read-only filesystem except temporary /tmp space, and environment variables from the project settings. Check runtime logs, confirm the variables are selected for Production, and redeploy after changing them.

Why do I get FUNCTION_INVOCATION_TIMEOUT on Vercel?

The function did not finish within its configured maximum duration. Common causes are a slow upstream API or database, an infinite loop, or a code path that never returns a response. Inspect runtime logs, measure the upstream call, return a response on every path, and raise maxDuration only when the work legitimately needs more time.

Can a Vercel Function continue work after sending the response?

Only when that work is explicitly scheduled with waitUntil in a Vercel Function or after() in supported Next.js versions. Unawaited promises are not a reliable background worker. Long or retryable jobs belong in a queue, workflow, daemon, or another durable worker pattern.