Handle Dependencies

A 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 prepackage 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:

const uuid = require('uuid');

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

Installing Node.js modules with npm

The easiest way to install a Node.js 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.js 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 in any local unit tests.

Loading Node.js modules

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

Send feedback about...

Need help? Visit our support page.