How to increase timeout limit on Vercel Serverless functions – Timeout

by
Alexei Petrov
javascript next.js serverless timeout vercel

Quick Fix: Verify the usage of App Router or Pages Router and adjust the configuration accordingly. Set the maxDuration value in the function’s configuration to extend the timeout limit. Additionally, configure the maximum duration for all functions in vercel.json if needed.

The Problem:

A Node.js function deployed on Vercel is taking longer than 60 seconds to execute, exceeding the default timeout limit. Despite attempts to increase the timeout limit using both inline function configuration and a vercel.json configuration file, the function still times out after 60 seconds. The developer has verified that they are on a pro Vercel plan and are using the latest versions of Next.js and Node.js. What is the issue preventing the timeout limit from being successfully increased?

The Solutions:

Solution 1: Using Configuration Object

For the Pages Router, create a file named [file-name].config.js in the /pages/api/[file-name] directory. Inside this file, add the following configuration object:

export const config = {
  maxDuration: 300, // 5 minutes in seconds
};

For the App Router, create a file named [file-name].route.ts in the /app/api/[file-name] directory. Inside this file, add the following:

export const maxDuration = 300; // 5 minutes in seconds
export const dynamic = 'force-dynamic';

export function GET(request: Request) {
  return new Response('{}', { status: 200 });
}

Solution 2: Using vercel.json

Create a vercel.json file in the root directory of your project and add the following configuration:

{
  "functions": {
    "pages/api/**": {
      "maxDuration": 300
    }
  }
}

This will override the default maximum duration of 60 seconds for all API routes in your project.

Q&A

Is there a difference in setting maxDuration a file(s) vs setting it in the vercel.json file at the top level of your project?.

Yes. In the vercel.json file, you’re setting the max duration of the function for your whole project.

How long can we set the maximum execution duration for a NextJS serverless function using Vercel App Router or Pages Router?.

The maximum allowed is 10 minutes.

How can we specify the timeout duration of a Pages Router function when using NextJS/.

You can specify the timeout duration of a Pages Router function in the export const config object of your function file.

Video Explanation:

The following video, titled "Build a GPT-3 AI app with Next.js and Vercel Edge Functions ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Hassan El Mghari (@HassanElMghari) Vercel Developer Advocate, explains how to build a GPT-3 powered AI application with OpenAI, Next.js, ...