With Vercel, you can deploy Serverless Functions, which are pieces of code written with backend languages that take an HTTP request and provide a response.
You can use Serverless Functions to handle user authentication, form submission, database queries, custom slack commands, and more.
Deploying Serverless Functions
To deploy Serverless Functions without any additional configuration, you can put files with extensions matching supported languages and exported functions in the /api
directory at your project's root.
/pages/api
directory instead.Read more about API functionality with Next.js.Sometimes, you need to place extra code files, such as utils.js
, inside the /api
folder. To avoid turning them into API endpoints, prefix such files with an underscore, _utils.js
. Files with the underscore prefix are not turned into Serverless Functions.
Then, push to your connected Git repository using a Vercel for Git to receive a deployment automatically. You can deploy Serverless Functions to dozens of regions across the world.
Example Serverless Function with Next.js
To deploy a Next.js API Route as a Serverless Functions, you can create a new file:
// pages/api/index.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(
request: NextApiRequest,
response: NextApiResponse,
) {
response.status(200).json({
body: request.body,
query: request.query,
cookies: request.cookies,
});
}
An example Next.js API Route deployed as a Serverless Function.
The above example echoes the body
, path query
, and cookies
, passed with the request object, as a JSON object using helper methods provided through the Request and Response.
Next, push to your connected repository using Vercel for Git to instantly deploy your API.
More Examples and Supported Languages
For all supported languages, see the Supported Languages for Serverless Functions documentation.
More examples of applications you can deploy paired with Serverless Functions can be found in the Vercel repository on GitHub.
You can get started with many of the Vercel examples by deploying them from the Quickstarts section.
Environment Variables
You can use Environment Variables inside your Serverless Functions, both locally with vercel dev
as well as deployed to Preview and Production environments.
For example, create an .env
file locally:
CLIENT_ID="your-value"
CLIENT_SECRET"your-value"
.env.local
is not currently supported with vercel dev
, so ensure you are using .env
. You should not commit this file to git. Ensure .env
is added to your .gitignore
file.
Then, you can access Environment Variables inside your Function when using vercel dev
:
import fetch from 'node-fetch';
export default async function handler(request, response) {
const res = await fetch('https://...', {
method: 'POST',
body: JSON.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
}),
headers: { 'Content-Type': 'application/json' },
});
const data = await res.json();
return response.status(200).json({ data });
}
Using Environment Variables in your Serverless Function.
Finally, add your Environment Variables to your Project Settings for use in Preview and Production environments.
Path Segments
Deploying Serverless Functions with Vercel gives you the ability to use path segments through file names instead of a complex routes file.
Any supported languages can utilize path segments. Creating a file in the /api
directory and wrapping the filename in square brackets, such as [name].js
will provide you with a file that takes a path segment and gives it to the function when requested with a value.
req.query
object under the key used for the file name.When using path segments, any dynamic filename can be used, this is indicated by the use of square brackets. The filename for the path segment is used solely for the purpose of providing a key name for accessing the value on the req.query
object.
For example, creating a name
directory (within /api
) that contains a [name].ts
file will allow you to receive the path segment entered when accessing /api/name/your-name
on the req.query.name
object.
The following Next.js example uses the path segment in its functionality when requested:
// [name].ts
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(
request: NextApiRequest,
response: NextApiResponse,
) {
const { name } = request.query;
response.end(`Hello ${name}!`);
}
An example Next.js API Route deployed as a Serverless Function that takes a name path segment and returns a string using it.
Execution Timeout
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.
Timeout conditions checklist
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.
Error Logs
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.
Local Development
Vercel provides an additional command with Vercel CLI to help you develop Serverless Functions locally by replicating the production environment on Vercel with your localhost.
If you have an api
directory like the above examples on this page, you can run the following command to start a local development environment that supports your serverless API and allows you to develop locally, just make sure to install your project's dependencies first with your dependency manager of choice (pnpm
, yarn
, and npm
are all supported by default):
vercel dev
Starting a local development environment using Vercel CLI, for Serverless Functions.
If you would like to override the dev
command, you can do so from the Build & Development Settings of your project.
Logging Serverless Functions
Each deployment at Vercel has a Functions section where you can see the calls to your Serverless Functions in real time. In order to log the functions properly, leave the Functions section open while your deployment is being accessed in the browser.
View of function activity (real-time) in the deployment.
Using the dropdown menu you can filter the logs so only a specific function is being shown. Mainly, all the paths defined by the files placed under the /api
folder.
Next.js logs
In Next.js projects, the functions listed are those API Routes defined by the files placed in pages/api
folder. 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.
Bundling Serverless Functions
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 via 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.
{
"functions": {
"pages/api/hello.js": {
"memory": 3008,
"maxDuration": 60
},
"pages/api/another.js": {
"memory": 1024,
"maxDuration": 30
}
}
}
An example of a Serverless Function configuration.
Advanced Usage
For an advanced configuration and structure, you can create a vercel.json
file to use Runtimes and other customizations.
We do, however, recommend using the api
directory to keep things simple for your project.
Technical Details
CPU Calculation
Serverless Functions are allocated CPU power according to the amount of memory configured for them.
For example, with 1,792MB memory configured, a Serverless Function will have the equivalent of one vCPU.
Limits
- Serverless Function Size
- Serverless Function Memory
- Serverless Function Concurrency
- Serverless Function Payload Size Limit
- Serverless Function Duration
Related
For more information on what to do next, we recommend the following articles: