Summary
"504: GATEWAY_TIMEOUT. Code: MIDDLEWARE_INVOCATION_TIMEOUT" on Vercel means your Next.js middleware did not return a response in time, so Vercel cut it off. Because middleware runs before every matched request, one slow call inside it can take down whole sections of a site at once: pages, API routes and sometimes static files.
Middleware is meant to be quick: read a cookie, rewrite or redirect, add a header. The timeout almost always comes from network work done inside it, such as session lookups, database queries, feature-flag or geolocation API calls, or fetching signing keys, with no timeout of its own. This guide shows how to find that call and move it. If you would rather hand it over, SazM offers an affordable Next.js and Vercel fix for a fixed $99 price, delivered within 48 hours, entirely in writing: no calls, no project manager, one senior developer.
Confirm It Is the Middleware
MIDDLEWARE_INVOCATION_TIMEOUT is different from FUNCTION_INVOCATION_TIMEOUT. The first is your middleware.ts (called proxy.ts from Next.js 16), the second is a page, route handler or API function. If you see the function version, see Vercel FUNCTION_INVOCATION_TIMEOUT (504).
Check where the time goes:
- In the Vercel dashboard, open the project's Logs, filter to the failing path, and look for middleware entries with long durations.
- From the CLI:
vercel logs <deployment-url>while you reproduce the error. - Note whether it fails on every request, only for signed-in users, only in some regions, or only after a deploy. Each points to a different external call.
Quick Fix Breakdown (DIY)
- Find every
awaitin the middleware. Eachfetch, database client or SDK call is a candidate. Log the time around each one:
const t = Date.now();
const res = await fetch(SESSION_URL, { headers });
console.log('session lookup ms', Date.now() - t);
- Give every network call its own timeout, and decide what happens when it fails: let the request through, or send the user to sign in. Never let it wait forever:
const res = await fetch(SESSION_URL, {
headers,
signal: AbortSignal.timeout(2000),
}).catch(() => null);
if (!res?.ok) {
return NextResponse.redirect(new URL('/login', request.url));
}
- Run middleware only where it is needed. A broad matcher runs it for images, scripts and assets too, multiplying the load on whatever it calls:
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|jpeg|svg|webp|ico)$).*)'],
};
- Check tokens locally instead of over the network. Verify a signed session cookie or JWT in the middleware, and cache the signing keys rather than fetching them on every request. With
jose,createRemoteJWKSetkeeps the keys between requests on a warm instance. - Move data work out of middleware. Database queries, user profile loads and permission lookups belong in the page, layout or route handler, where caching and longer limits apply. Keep middleware to cookie checks, redirects, rewrites and headers.
- Look at the slow dependency itself. An auth provider, database or API in a region far from where the middleware runs adds latency to every call. Check its status page and response times while the error is happening.
Fix the middleware first. Raising limits elsewhere does not help, because the middleware timeout is separate from your functions' maximum duration.
Hand It Over: $99 Fixed, Within 48 Hours
Middleware timeouts are hard to pin down because they depend on traffic, region and a third-party service you do not control. One developer who traces the slow call, adds safe timeouts and moves the work to the right place ends the outages.
What you get for $99:
- A fixed price agreed before work starts. One issue, one flat fee, no hourly meter.
- Delivery within 48 hours of access, tested on a Vercel preview deployment before anything reaches production.
- Fully written, fully async. You send the failing URLs, the error code, your
middleware.tsand what changed recently. You get questions, progress and proof in writing. There are no calls, meetings or project managers. - Written proof it works: which call was slow, what changed, and request timings before and after.
- Money-back guarantee if the agreed root cause cannot be resolved.
- Safe access only: repository access and a Vercel team role you can remove afterwards. Never send tokens or passwords through the inquiry form.
Behind it: 20+ years in production (since Oct 2006) and 100+ projects in the portfolio.
Get your Next.js error fixed for $99 → · Queue an urgent fix · See past projects
Frequently Asked Questions
What does MIDDLEWARE_INVOCATION_TIMEOUT mean on Vercel?
Your Next.js middleware took too long to return a response, so Vercel stopped it and returned a 504. It is almost always caused by a slow network call inside the middleware, such as a session, database or API request without its own timeout.
What is the difference between MIDDLEWARE_INVOCATION_TIMEOUT and FUNCTION_INVOCATION_TIMEOUT?
The middleware error comes from middleware.ts (or proxy.ts in Next.js 16), which runs before matched requests. The function error comes from a page, route handler or API function that ran past its maximum duration. They have separate limits and separate fixes.
Can I increase the middleware timeout?
Treat the limit as fixed and design for it. Middleware should finish in a fraction of a second. Add timeouts to every network call, narrow the matcher, and move data loading into pages or route handlers.
Why does the 504 only happen sometimes?
It follows the slow dependency. When an auth provider, database or API slows down, every request that waits on it in middleware times out at once. At quiet times the same code finishes in time, which hides the problem.
How much does it cost to fix a Vercel middleware timeout?
SazM fixes one issue for a fixed $99, delivered within 48 hours, with a money-back guarantee if the agreed root cause cannot be resolved. Typical agency hourly rates are higher and open-ended, while very low marketplace gig prices rarely include root-cause diagnosis, a preview-deployment test or a guarantee.