Common Next.js errors504: FUNCTION_INVOCATION_TIMEOUT on Vercel
504: GATEWAY_TIMEOUT. Code: FUNCTION_INVOCATION_TIMEOUT. A page, route handler or Server Action ran for longer than the function was allowed to, so Vercel stopped it. It often appears only in production, where real data is bigger and APIs are slower than on your laptop.
Common causes
- A slow third-party API or database query with no timeout of its own.
- Requests made one after another that could run at the same time.
- Work the visitor doesn't need to wait for (emails, analytics, webhooks) done before responding.
- A database connection that hangs because the pool is exhausted.
How to fix it
Run independent requests together, give outside calls their own timeout, and move follow-up work to after the response:
app/api/order/route.ts import { after } from 'next/server'
export async function POST(req: Request) {
const order = await req.json()
const [stock, price] = await Promise.all([
getStock(order.sku),
fetch(PRICES_URL, { signal: AbortSignal.timeout(3000) }).then((r) => r.json()),
])
const saved = await saveOrder(order, stock, price)
after(() => sendReceipt(saved)) // runs once the response has gone
return Response.json(saved)
}
If the work really does take a while, raise the limit for that route with export const maxDuration = 60 (seconds; the ceiling depends on your Vercel plan). For anything longer, hand it to a background job or queue instead of keeping the request open.