Skip to content

The Node.js Runtime, by default, builds and serves Serverless Functions within the /api directory of a project, providing the files have a file extension of .js, .mjs, or .ts.

A Node.js Serverless Function must export a default function handler, for example:

api/hello.js
export default function handler(request, response) {
  const { name = 'World' } = request.query;
  return response.send(`Hello ${name}!`);
}

An example serverless Node.js function using the Request and Response objects.

The Node.js Runtime also supports asynchronous functions.

If you need more advanced behavior, such as a custom build step or private npm modules, see the Advanced Node.js Usage section.

Whenever a new Project is created, the latest Node.js LTS version available on Vercel at that time is selected for it.

This selection will be reflected within the Node.js Version section on the General page of the Project Settings. If needed, you can also customize it there:

Selecting a custom Node.js version for your Project.
Selecting a custom Node.js version for your Project.
Selecting a custom Node.js version for your Project.

Currently, the following Node.js versions are available:

Only major versions are available. Vercel will automatically roll out minor and patch updates if needed (for example in the case that a security issue needs to be fixed).

Defining the node property inside engines of a package.json file will override the selection made in the Project Settings. Please note that Vercel will only use the available major versions—we will print a Build Step warning if the package.json specified version does not match our available major versions. Also, please avoid greater than ranges, such as >14.x or >=14, because this will match semver major versions of Node.js once available, which contain breaking changes.

For example, the range >16.2.0 would match the versions 16.2.5, 16.3.0, and 18.0.0.

In order to find out which Node.js version your Deployment is using, run node -v in the Build Command or log the output of process.version.

For dependencies listed in a package.json file at the root of a project, the following behavior is used:

  • If pnpm-lock.yaml is present, pnpm install is executed
    • If "lockfileVersion": 5.4 is present in the lock file, pnpm 7 is used
    • Otherwise, pnpm 6 is used
  • If package-lock.json is present, npm install is executed
    • If "lockfileVersion": 2 is present in the lock file, npm 8 is used
    • Otherwise npm 6 is used
  • If bun.lockb is present, the Install Command is bun install
    • Bun 1 is used
  • Otherwise, yarn install is executed

If you need to select a specific version of a package manager, see corepack.

The Node.js Runtime supports files ending with .ts inside of the /api directory as TypeScript files to compile and serve when deploying.

An example TypeScript file that exports a default Node.js function and takes in the standard Node.js Request and Response objects is as follows:

api/hello.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';
 
export default function (request: VercelRequest, response: VercelResponse) {
  const { name = 'World' } = request.query;
  response.send(`Hello ${name}!`);
}

An example serverless Node.js function written in TypeScript, using types from the @vercel/node module for the helper methods.

The VercelRequest and VercelResponse imports in the above example are types that we provide for the Request and Response objects, including the helper methods with Vercel. These types can be installed from npm with the following command:

npm install @vercel/node --save-dev

Installing @vercel/node for types when using Node.js on Vercel.

You can also use a tsconfig.json file at the root of your project to configure the TypeScript compiler. Most options are supported aside from "Path Mappings" and "Project References".

Each request to a Node.js Serverless Function gives access to Request and Response objects. These objects are the standard HTTP Request and Response objects from Node.js.

Vercel additionally provides helper methods inside of the Request and Response objects passed to Node.js Serverless Functions. These methods are:

method
description
object
request.query
An object containing the request's query string, or {} if the request does not have a query string.
Request
request.cookies
An object containing the cookies sent by the request, or {} if the request contains no cookies.
Request
An object containing the body sent by the request, or null if no body is sent.
Request
response.status(code)
A function to set the status code sent with the response where code must be a valid HTTP status code. Returns response for chaining.
Response
response.send(body)
A function to set the content of the response where body can be a string, an object or a Buffer.
Response
response.json(obj)
A function to send a JSON response where obj is the JSON object to send.
Response
response.redirect(url)
A function to redirect to the URL derived from the specified path with status code "307 Temporary Redirect".
Response
response.redirect(statusCode, url)
A function to redirect to the URL derived from the specified path, with specified HTTP status code.
Response

The following Node.js Serverless Function example showcases the use of request.query, request.cookies and request.body helpers:

api/hello.js
module.exports = (request, response) => {
  let who = 'anonymous';
 
  if (request.body && request.body.who) {
    who = request.body.who;
  } else if (request.query.who) {
    who = request.query.who;
  } else if (request.cookies.who) {
    who = request.cookies.who;
  }
 
  response.status(200).send(`Hello ${who}!`);
};

Example Node.js Serverless Function using the request.query, request.cookies, and request.body helpers. It returns greetings for the user specified using request.send().

If needed, you can opt-out of Vercel providing helpers using advanced configuration.

We populate the request.body property with a parsed version of the content sent with the request when possible.

We follow a set of rules on the Content-type header sent by the request to do so:

Content-Type header
Value of request.body
No header
undefined
application/json
An object representing the parsed JSON sent by the request.
application/x-www-form-urlencoded
An object representing the parsed data sent by with the request.
text/plain
A string containing the text sent by the request.
application/octet-stream
A Buffer containing the data sent by the request.

With the request.body helper, you can build applications without extra dependencies or having to parse the content of the request manually.

The request.body helper is set using a JavaScript getter. In turn, it is only computed when it is accessed.

When the request body contains malformed JSON, accessing request.body will throw an error. You can catch that error by wrapping request.body with try...catch:

api/hello.js
try {
  request.body;
} catch (error) {
  return response.status(400).json({ error: 'My custom 400 error' });
}

Catching the error thrown by request.body with try...catch.

In order to use this Runtime, no configuration is needed. You only need to create a file inside the api directory.

The entry point for src must be a glob matching .js, .mjs, or .ts files that export a default function.

Add an Environment Variable with name NODEJS_HELPERS and value 0 to disable helpers.

To install private npm modules, define NPM_TOKEN as an Environment Variable in your Project.

Alternatively, define NPM_RC as an Environment Variable with the contents of ~/.npmrc.

In some cases, you may wish to include build outputs inside your Serverless Function. You can run a build task by adding a vercel-build script within your package.json file, in the same directory as your Serverless Function or any parent directory. The package.json nearest to the Serverless Function will be preferred and used for both Installing and Building.

For example:

package.json
{
  "scripts": {
    "vercel-build": "node ./build.js"
  }
}

An example package.json file with a vercel-build script to execute in the build step.

Along with build script named build.js:

build.js
const fs = require('fs');
fs.writeFile('built-time.js', `module.exports = '${new Date()}'`, (err) => {
  if (err) throw err;
  console.log('Build time file created successfully!');
});

An example Node.js file, executed by the above package.json build script.

And a .js file for the built Serverless Functions, index.js inside the /api directory:

api/index.js
const BuiltTime = require('./built-time');
module.exports = (request, response) => {
  response.setHeader('content-type', 'text/plain');
  response.send(`
    This Serverless Function was built at ${new Date(BuiltTime)}.
    The current time is ${new Date()}
  `);
};

An example Node.js Serverless Function, using information from the created file from the build script.

A Node.js Runtime entrypoint can contain one of the following to retain legacy serverful behavior:

  • Default export server, such as module.exports = http.createServer((request, response) => { response.end('hello') }).
  • Server listens on a port, such as http.createServer((request, response) => { response.end('hello') }).listen(3000).

The Node.js Runtime provides a way to opt into the AWS Lambda API. This is useful if you have existing Serverless Functions you wish to deploy to Vercel but do not want to change the API.

api/hello.js
exports.handler = async function (event, context, callback) {
  return {
    statusCode: 200,
    headers: {},
    body: 'Hello world',
  };
};
vercel.json
{
  "build": {
    "env": {
      "NODEJS_AWS_HANDLER_NAME": "handler"
    }
  }
}

The value of the environment variable needs to match the name of the method that is exported from your Serverless Functions.

Express.js is a popular framework used with Node.js. For information on how to use Express with Vercel, see the guide: Using Express.js with Vercel.

Last updated on February 6, 2023