Handling Dependencies

A Cloud Function is allowed to use other Node.js modules as well as other local data. Dependencies in Node.js are managed with npm and expressed in a metadata file called package.json shipped alongside your function. You can either pre-package fully materialized dependencies within your function package, or declare them in the package.json file and Cloud Functions will download them for you when you deploy. You can learn more about the package.json file from the npm docs.

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:

Node.js

const uuid = require('uuid');

// Return a newly generated UUID in the HTTP response.
exports.getUuid = function (req, res) {
  res.send(uuid.v4());
};

Installing Node modules with npm

The easiest way to install a Node module is to use the npm install --save command in your functions folder. For instance, to add the uuid module to your Cloud Functions project, use a command like the following:

npm install --save uuid

This combines two steps:

  1. It adds the latest copy of the node module as a dependency in your package.json file. This is very important: Cloud Functions only install 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 in any local unit tests.

Loading Node modules

Just as you would use require('uuid') to load the uuid module, you can use the require function to load any Node module you have installed. The require function takes the name of the node module and returns that module's exports object.

Send feedback about...

Cloud Functions Documentation