Specifying dependencies in Node.js

A function is allowed to use external Node.js modules as well as local data. Dependencies in Node.js are managed with npm and expressed in a metadata file called package.json.

To specify a dependency for your function, add it to your package.json file. If you are deploying through the gcloud command-line tool, you can also pre-install dependencies and deploy them alongside your function. By default, the node_modules folder is added to your .gcloudignore file and is not uploaded as part of your deployment. To deploy pre-installed dependencies, remove node_modules/ from the .gcloudignore file before deploying your function.

After you deploy your function, Cloud Functions installs dependencies declared in the package.json file using the npm install command. In the Node.js 8 runtime, if a yarn.lock file exists, the yarn install command is used instead.

The Node.js runtime also includes a number of system packages in the execution environment. If your function uses a dependency that requires a package that is not listed, you can request a package.

In this example, a dependency is listed in the package.json file:

  "dependencies": {
    "uuid": "^3.0.1"

The dependency is then imported in the function:

const uuid = require('uuid');

// Return a newly generated UUID in the HTTP response.
exports.getUuid = (req, res) => {

Using npm to install Node.js modules

The easiest way to install a Node.js module is to use the npm install command in the folder containing your Cloud Function. For instance, the following command adds the uuid module:

npm install uuid

This combines two steps:

  1. It marks the latest version of the module as a dependency in your package.json file. This is very important: Cloud Functions only installs modules that are declared in your package.json file.
  2. It downloads the module into your node_modules directory. This lets you use the module when developing locally.

If you don't have npm installed on your machine, get npm.

Loading Node.js modules

Use the Node.js require() function to load any Node.js module you have installed. You can also use the require() function to import local files you deploy alongside your function.

Using private modules

In order to use a private npm module, you must provide credentials (auth token) for the npm registry in a .npmrc file located in the function's directory. The npm documentation explains how to create custom read-only access tokens. We discourage using the .npmrc file created in the home directory because it contains a read-write token. Write permissions are not required during deployment, and could pose a security risk.

Do not include the .npmrc file if you're not using private repositories, as it can increase the deployment time for your functions.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation