How-to
Advanced Node.js Usage
Learn about advanced configurations for Serverless Functions on Vercel.Table of Contents
Next.js (/app)
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:
- From the dashboard, select your project and go to the Settings tab.
- Select Environment Variables from the left side in settings.
- 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. - 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:
- From the dashboard, select your project and go to the Settings tab.
- Select Environment Variables from the left side in settings.
- Add a new environment variable with the Key:
NPM_TOKEN
and enter your npm token as the value. Alternatively, defineNPM_RC
as an Environment Variable with the contents of~/.npmrc
. - 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:
- Add a
vercel-build
script within yourpackage.json
file, in the same directory as your Serverless Function or any parent directory. Thepackage.json
nearest to the Serverless Function will be preferred and used for both installing and building:
package.json
{
"scripts": {
"vercel-build": "node ./build.js"
}
}
- 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!');
});
- 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
Was this helpful?