Skip to content
Last updated on February 17, 2023
7 min read

Serverless Functions Overview

Vercel Serverless Functions enable running code on-demand without needing to manage your own infrastructure, provision servers, or upgrade hardware.

Serverless Functions are available on all plans

Serverless Functions enable developers to write functions in JavaScript and other languages to handle user authentication, form submissions, database queries, custom Slack commands, and more.

These Functions are co-located with your code and part of your Git workflow. As traffic increases, they automatically scale up and down to meet your needs, helping you to avoid paying for always-on compute with no downtime.

Serverless Functions location within Vercel infrastructure.

Serverless Functions can be deployed to dozens of regions across the world. You can deploy them to a single region or to multiple regions to improve latency and availability.

Checkout the Serverless Functions Quickstart guide to learn more.

Sometimes, you need to place extra code files, such as utils.js or my-types.d.ts, inside the /api folder. To avoid turning these files into Serverless Functions, Vercel ignores files when prefixed with the following characters:

  • Files that start with an underscore, _, are ignored
  • Files that start with . are ignored
  • Files that end with .d.ts are ignored

If your file is prefixed with any of the above, it will not be turned into an Serverless Function.

Serverless Functions on Vercel enforce a maximum execution timeout. This means that the function must respond to an incoming HTTP request before the timeout has been reached.

If the Serverless Function does not respond to the HTTP request within the timeout, then a 504 error status code is returned with the error code FUNCTION_INVOCATION_TIMEOUT.

The timeout is determined by the "Serverless Function Execution Timeout (Seconds)" limit, which is based on the plan that the Personal Account, or Team has enabled when creating the deployment.

If you are seeing an execution timeout error, check the following possible causes:

  • The function isn't returning a response: The function must return an HTTP response, even if that response is an error. If no response is returned, the function will time out.
  • The function is taking too long to process a request: Check that any API, or database requests you make in your function, are responding within the "Serverless Function Execution Timeout (Seconds)" limit applicable to your plan.
  • You have an infinite loop within your function: Check that your function is not making an infinite loop at any stage of execution.
  • Upstream errors: Check that any external API or database that you are attempting to call doesn't have any errors.

For more information on Serverless Functions timeouts, see What can I do about Vercel Serverless Functions timing out?

Logs are treated as an "error" when Serverless Functions do not return a correct response by either crashing or timing out. The last 2,000 error logs are stored and persisted indefinitely.

When building Next.js applications on Vercel, you can continue to use the native next dev command and local development server to iterate on your API Routes.

next dev

Starting the Next.js local development server.

You can use runtime logs to view all the logs related to your serverless functions.

You can filter to see Serverless Functions by selecting Serverless under Type. You can also use the Functions section to search by and view the logs for specific functions.

When a Serverless Function on a specific path receives a user request, you may see more than one log when the application renders or regenerates the page.

This can occur in the following situations:

  1. When a new page is rendered
  2. When you are using Incremental Static Regeneration (ISR)

In the case of ISR, multiple logs are the result of:

  • A stale page having to be regenerated
  • On-demand ISR happening with fallback set as blocking

For a stale page, it happens because there are two things that need to be rendered:

  1. The HTML, which is used when you navigate to the page URL in your browser
  2. The JSON, which is used when you navigate to the page through a link as a Single Page App (SPA) transition

Both the HTML and JSON need to be in sync and rendered at the same time. Otherwise, you will see different behavior between browser navigation and a SPA transition.

For on-demand ISR, the following happens:

  • Synchronous rendering to load the page (HTML, for example) on-demand when it was requested
  • Revalidate the 2 versions (HTML, JSON) in the background

In Next.js projects, the functions listed are those API Routes defined by the files placed in pages/api/**/*.{js,ts} or app/**/route.{js,ts}. However those pages that require server side rendering, mainly by calling getServerSideProps, will also be available both in the filter drop down and the real time logs.

In order to optimize resources, there is an internal process that bundles as many Serverless Functions as possible into a single Lambda. Such a feature is currently only enabled for Next.js, but it will be enabled in other scenarios in the future.

This internal process shouldn't affect the developer in any case. However, if a configuration on the functions property is present in current versions of Next.js (>= v10.0.9), then the internal process will bundle functions based on the configuration first. The remaining functions will be bundled together optimizing for how many functions are created. In the following example, pages/api/hello.js will be bundled separately from pages/api/another.js since each has a different configuration.

vercel.json
{
  "functions": {
    "pages/api/hello.js": {
      "memory": 3008,
      "maxDuration": 60
    },
    "pages/api/another.js": {
      "memory": 1024,
      "maxDuration": 30
    }
  }
}

An example of a Serverless Function configuration.

For an advanced configuration, you can create a vercel.json file to use Runtimes and other customizations. To view more about the properties you can customize, review the advanced usage section of Runtimes and Project config with vercel.json.

For information on improving the performance of your Serverless Functions and understanding how to determine if the latency increase is from a cold start, see How can I improve serverless function cold start performance on Vercel?

Serverless Functions allow you to access classes from standard Web APIs.

The following example demonstrates a Serverless Function that uses a URLPattern object to match a request URL against a pattern.

api/lookup.js
const pattern = new URLPattern({ pathname: '/api/books/:id' });
 
if (pattern.test(request.url)) {
  const result = pattern.exec(request.url);
  return lookupBook(result.pathname.groups.id);
}

Both Serverless and Edge Functions support standard Web API function signatures. A function's signature is the collection of general information about a function, including the values and types of its parameters and return values.

By supporting Web API function signatures in Serverless and Edge Functions, Vercel is making the two runtimes easier to port code between and develop libraries for.

Here's an example of a Serverless Function that returns a Web API Response object:

response
export default async function handler(request, event) {
  return Response.json({
    success: true,
  });
}

Serverless Functions are archived when they are not invoked:

Archived Functions will be unarchived when they're invoked, which can make the initial cold start time at least 1 second longer than usual.

Serverless Functions are allocated CPU power according to the amount of memory configured for them.

For example, with 1,769MB memory configured, a Serverless Function will have the equivalent of one vCPU.

For more information on what to do next, we recommend the following articles: