Writing Cloud Functions

Google Cloud Functions are written in JavaScript, and execute in a Node.js runtime.

A Cloud Function is a Module

When creating a Cloud Function, your function's source code must be exported in a Node.js module. The module will be 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 may 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 will work as long the require() call can load your exported function.

The Cloud Functions Runtime

The Cloud Functions Node.js execution environment follows the Node "LTS" releases, starting with the v6 LTS release published on 2016-10-18. The current Node.js version running in Cloud Functions is Node v6.11.1.

Types of Cloud Functions

Cloud Functions come in two distinct variants: foreground (HTTP) and background.

HTTP Functions

You invoke HTTP functions from standard HTTP requests. These HTTP requests wait for the response and support handling of common HTTP request methods like GET, PUT, POST, DELETE and OPTIONS. When you use Cloud Functions, a TLS certificate is automatically provisioned for you, so all HTTP Functions can be invoked via a secure connection.

For details, see Writing HTTP Functions.

Example:

Node.js

/**
 * HTTP Cloud Function.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.helloHttp = function helloHttp (req, res) {
  res.send(`Hello ${req.body.name || 'World'}!`);
};

Background Functions

You can use background functions to handle events from your Cloud infrastructure, such as messages on a Google Cloud Pub/Sub topic, or changes in a Google Cloud Storage bucket.

For details, see Writing Background Functions.

Example:

Node.js

/**
 * Background Cloud Function.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloBackground = function helloBackground (event, callback) {
  callback(null, `Hello ${event.data.name || 'World'}!`);
};

Next steps

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Functions Documentation