The Node.js 8 Runtime

The Cloud Functions Node.js 8 runtime is based on Node.js version 8.11.1. For instructions on how to how to prepare your local machine for Node.js development, see Setting Up a Node.js Development Environment.

Selecting the runtime

You can select the Node.js 8 runtime for your function during deployment.

gcloud

If you are using the gcloud command-line tool, you can specify the runtime by using the --runtime parameter. For example:

gcloud functions deploy NAME --runtime nodejs8 --trigger-http

For more arguments that you can specify when you are deploying, see Deploy using the gcloud tool.

Console

If you are using the GCP Console, you can select the runtime when you create and deploy a function.

  1. In the GCP Console, go to the Cloud Functions Overview page.

    Go to the Cloud Functions Overview page

    Make sure that the project for which you enabled Cloud Functions is selected.

  2. Click Create Function.

  3. Under Runtime, select Node.js 8.

Execution environment

The execution environment includes the runtime, the operating system, packages, and a library that invokes your function.

Base image

For the Node.js 8 runtime, Cloud Functions uses an execution environment based on Ubuntu 18.04. Updates to the language runtime are done automatically (unless otherwise notified), and include changes in the definition of the base image.

HTTP library

The Node.js 8 runtime uses ExpressJS to handle incoming requests. This helper invokes your function in response to an incoming request and takes care of other details, such as handling HTTP.

Updates to the execution environment

This runtime receives automatic updates to the version of Node.js. For example, Cloud Functions currently uses Node.js version 8.11.1. When a new version of Node.js 8 is released to the language community, the runtime version might be updated.

Similarly, Cloud Functions might apply updates to other aspects of the execution environment, such as the operating system, packages, and other elements of the environment. These updates help keep your function secure.

Cloud Functions file naming

When creating a function, your source code must be exported in a Node.js module. The module is loaded using a require() call, so functions are typically contained within a simple index.js file.

The following example configurations are permissible, but other configurations might work as well:

  • An index.js file that exports one or more functions.
  • An app.js file that exports one or more functions, with a package.json file that contains "main": "app.js".
  • An index.js file that imports one or more functions from a foo.js file and then exports one or more functions.

Any configuration works as long the require() call can load your exported function.

Specifying 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.

If you are deploying through gcloud, Cloud Functions downloads dependencies declared in package.json using npm. You can also prepackage fully materialized dependencies alongside your function. By default, node_modules is added to .gcloudignore and is not uploaded as part of your deployment.

If you are deploying through the Firebase CLI, the local node_modules folder is ignored, and you must specify your dependencies in package.json. 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 = (req, res) => {
  res.send(uuid.v4());
};

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.

Loading Node.js modules

Just as you can depend on third-party libraries like the uuid module, you can use require (JavaScript) 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.

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.

Async/await

Node.js 8.x is the first LTS version of Node.js to support the async and await keywords. The following example shows a simple function that uses these new keywords:

const PubSub = require('@google-cloud/pubsub');
let ps;

/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {object} data The payload for the Pub/Sub message.
 * @param {object} context The context object for the event.
 */
exports.helloPubSub = async (data, context) => {
  ps = ps || new PubSub();
  try {
    const topicName = context.resource.name;
    const topic = ps.topic(topicName);

    // Get metadata for the topic
    // This will call the Pub/Sub API
    const data = await topic.getMetadata();
    const metadata = data[0];
    console.log(`Metadata: ${JSON.stringify(metadata)}`);
  } catch(err) {
    console.error(err);
  }
};

When this function is triggered by a message on a Cloud Pub/Sub topic, it extracts the topic name from the context object, gets metadata associated with the Cloud Pub/Sub topic, then prints that metadata to Stackdriver Logging. The function uses the await keyword to turn an asynchronous metadata request into a synchronous operation.

Using middleware to handle HTTP requests

Node.js HTTP Cloud Functions provide request and response objects that are compatible with ExpressJS to make consuming HTTP requests simple. Cloud Functions automatically reads the request body, so you will always receive the body of a request independent of the content type. This means that HTTP requests should be considered to have been fully read by the time your code is executed. The nesting of ExpressJS apps should be used with this caveat - specifically, middleware that expects the body of a request to be unread might not behave as expected.

Terminating background functions

Background functions expect you to signal that your function has completed. You can signal function completion in the following ways:

  • Return a value or a Promise
  • Wrap your function using the async keyword (which causes your function to implicitly return a Promise)
  • Invoke the function's callback argument

Migrating background functions from Node.js 6 to Node.js 8

If you already have a background function using Node.js 6 on Cloud Functions, you might notice that the signature for background functions has changed for Node.js 8. This section explains the change and provides a migration guide.

An example Node.js 6 background function might look as follows:

exports.nodeJS6BackgroundFunction = (event) => {
  let data = event.data;
  let context = event.context;
  // the rest of your function is unchanged
};

Note that the event argument contains data and context properties. In Node.js 8, the data and context properties have been extracted from the event object and are now included as part of the function signature. For example:

exports.nodeJS8BackgroundFunction = (data, context) => {
  // the rest of your function is unchanged
};

This change simplifies references to the data and context objects previously contained within the event argument. For more information, see Background function parameters.

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

Send feedback about...

Cloud Functions Documentation