Fix: 504 Gateway Timeout in Vercel Serverless Functions

The Symptom

Your API route (like an AI generation script, email sender, or heavy database query) works perfectly on your local machine. However, when deployed to Vercel, the browser hangs for exactly 10 to 15 seconds before crashing with this error:

504: GATEWAY_TIMEOUT
Code: FUNCTION_INVOCATION_TIMEOUT

The serverless function has exceeded its execution limit.

The Cure

Vercel places strict execution time limits on Serverless Functions to prevent runaway costs. You must explicitly request a longer execution time (up to your plan's maximum allowed limit).

Cure 1: Next.js App Router & API Routes

Export the maxDuration constant at the top of your specific route file.

javascript (route.js / api.js)
// Allow this specific route to run for up to 60 seconds
export const maxDuration = 60; 

export async function POST(request) {
  // Your long-running AI task or heavy DB query here
  const result = await heavyTask();
  return new Response(JSON.stringify(result), { status: 200 });
}

Cure 2: Pure Vanilla / vercel.json

If you are not using Next.js, define the limits in your vercel.json file at the root of your project.

json (vercel.json)
{
  "functions": {
    "api/long-task.js": {
      "maxDuration": 60
    }
  }
}

The Breakdown

Localhost does not have a hard timeout. A script can run for 5 minutes locally without failing. Vercel, however, kills hanging serverless functions to free up compute resources based on your billing tier:

If you set maxDuration = 300 while on the Hobby tier, your Vercel deployment will fail during the build process.

Prevention & Advanced Architectures

If your task regularly exceeds 60 seconds (like processing large video files or heavy AI generation), standard Serverless Functions are the wrong architecture. Consider these alternatives:

Developer Logs

Loading logs...