Advanced Node.js Usage

Learn about advanced configurations for Serverless Functions on Vercel.
Table of Contents

To use Node.js, create a file inside your project's api directory. No additional configuration is needed.

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

To disable helpers:

  1. From the dashboard, select your project and go to the Settings tab.
  2. Select Environment Variables from the left side in settings.
  3. Add a new environment variable with the Key: NODEJS_HELPERS and the Value: 0. You should ensure this is set for all environments you want to disable helpers for.
  4. Pull your env vars into your local project with the following command:
    terminal
    vercel env pull

For more information, see Environment Variables.

To install private npm modules:

  1. From the dashboard, select your project and go to the Settings tab.
  2. Select Environment Variables from the left side in settings.
  3. Add a new environment variable with the Key: NPM_TOKEN and enter your npm token as the value. Alternatively, define NPM_RC as an Environment Variable with the contents of ~/.npmrc.
  4. Pull your env vars into your local project with the following command:
    terminal
    vercel env pull

For more information, see Environment Variables.

In some cases, you may wish to include build outputs inside your Serverless Function. To do this:

  1. Add 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:
package.json
{
  "scripts": {
    "vercel-build": "node ./build.js"
  }
}
  1. Create the 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!');
});
  1. Finally, create 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()}
  `);
};
Last updated on September 7, 2024