Stay organized with collections Save and categorize content based on your preferences.

Create and deploy a HTTP Cloud Function by using Node.js

This guide takes you through the process of writing a Cloud Function using the Node.js runtime. There are two types of Cloud Functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

The sample shows how to create a simple HTTP function.

Guide structure

  1. Creating a GCP project using gcloud CLI
  2. Creating a function
  3. Specifying dependencies
  4. Deploying your function
  5. Testing your function

Creating a GCP project using gcloud CLI

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. Install and initialize the gcloud CLI.
  9. Update and install gcloud components:
    gcloud components update
  10. Prepare your development environment.

    Go to the Node.js setup guide

Creating a function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/helloworld
    cd ~/helloworld
    

    Windows

    mkdir %HOMEPATH%\helloworld
    cd %HOMEPATH%\helloworld
    
  2. Create an index.js file in the helloworld directory with the following contents:

    const functions = require('@google-cloud/functions-framework');
    const escapeHtml = require('escape-html');
    
    /**
     * Responds to an HTTP request using data from the request body parsed according
     * to the "content-type" header.
     *
     * @param {Object} req Cloud Function request context.
     * @param {Object} res Cloud Function response context.
     */
    functions.http('helloHttp', (req, res) => {
      res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
    });

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello World!" when no name is supplied.

Specifying dependencies

Dependencies in Node.js are managed with npm and expressed in a metadata file called package.json.

  1. Create a package.json file in the helloworld directory, either manually or by running the command:

    npm init
    
  2. Add the function's dependency, in this case the escape-html package, to your package.json file, either manually or by running the command:

    npm install escape-html
    

    Your package.json file should contain a section like the following:

    {
      ...
      "dependencies": {
        "escape-html": "^1.0.3"
      }
      ...
    }
    

    If you are creating your package.json file manually, you can copy the following contents into it:

    {
      "name": "nodejs-docs-samples-functions-hello-world",
      "version": "0.0.1",
      "private": true,
      "license": "Apache-2.0",
      "author": "Google Inc.",
      "repository": {
        "type": "git",
        "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
      },
      "engines": {
        "node": ">=12.0.0"
      },
      "dependencies": {
        "@google-cloud/debug-agent": "^7.0.0",
        "@google-cloud/functions-framework": "^3.1.0",
        "escape-html": "^1.0.3"
      },
      "devDependencies": {
        "@google-cloud/pubsub": "^3.0.0",
        "@google-cloud/storage": "^6.0.0",
        "gaxios": "^5.0.0",
        "mocha": "^10.0.0",
        "moment": "^2.24.0",
        "promise-retry": "^2.0.0",
        "sinon": "^15.0.0",
        "supertest": "^6.0.0",
        "uuid": "^9.0.0",
        "wait-port": "^1.0.4"
      }
    }
    

Deploying the function

To deploy the function with an HTTP trigger, run the following command in the helloworld directory:

gcloud functions deploy helloHttp --runtime nodejs18 --trigger-http --allow-unauthenticated

The --allow-unauthenticated flag lets you reach the function without authentication. To require authentication, omit the flag.

Testing the function

  1. When the function finishes deploying, take note of the httpsTrigger.url property or find it using the following command:

    gcloud functions describe helloHttp
    

    It should look like this:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
  2. Visit this URL in your browser. You should see a "Hello World!" message.

    Try passing a name in the HTTP request, for example by using the following URL:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

    You should see the message "Hello NAME!"

Viewing logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Cloud Logging UI, and via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command, followed by the name of the function:

gcloud functions logs read helloHttp

The output should resemble the following:

LEVEL  NAME       EXECUTION_ID  TIME_UTC                 LOG
D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:25.983  Function execution started
D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:26.001  Function execution took 19 ms, finished with status code: 200

Using the Logging dashboard

You can also view logs for Cloud Functions from the Google Cloud console.