Setting up Stackdriver Trace for Node.js

Stackdriver Trace can be enabled for Node.js applications using the Stackdriver Trace library for Node.js.

Installing the client library

  1. Before installing the Stackdriver Trace library for Node.js, make sure you've prepared your environment for Node.js development.

  2. The easiest way to install the Stackdriver Trace library for Node.js is with npm:

    npm install --save @google-cloud/trace-agent
  3. Import the Stackdriver Trace library for Node.js at the top of your application's main script or entry point before any other code:

    require('@google-cloud/trace-agent').start();

For more information or to report issues with the Stackdriver Trace library for Node.js, see the agent's source code repository.

Configuring the client library

You can customize the behavior of the Stackdriver Trace library for Node.js. See the library's configuration on GitHub for a list of possible configuration options. These options can be passed in the options object passed to the library's start method.

Running on Google Cloud Platform

The Stackdriver Trace library for Node.js should work without the need to manually provide authentication credentials for instances running on Google Cloud Platform, as long as the Stackdriver Trace API access scope is enabled on that instance.

App Engine flexible

On App Engine flexible environment, the Stackdriver Trace API access scope is enabled by default, and the Stackdriver Trace library for Node.js can be used without providing credentials or a project ID.

App Engine standard

On App Engine standard environment, the Stackdriver Trace API access scope is enabled by default, and the Stackdriver Trace library for Node.js can be used without providing credentials or a project ID.

Google Kubernetes Engine

To use Trace with GKE, add the trace.append OAuth access scope when you create your cluster.

To create a cluster using gcloud, do the following:

  1. (Optional) Update gcloud to the latest version:
    gcloud components update
  2. Set your default project ID:
    gcloud config set project [PROJECT_ID]
  3. If you're working with zonal clusters, set your default compute zone:
    gcloud config set compute/zone [COMPUTE_ZONE]
  4. If you're working with regional clusters, set your default compute region:
    gcloud config set compute/region [COMPUTE_REGION]
  5. Issue the create command:
    gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/trace.append

For more detailed information on creating a cluster, see Creating a cluster.

Compute Engine

For Compute Engine VM instances, you need to explicitly enable the trace.append Stackdriver Trace API access scope for each VM instance. When creating a new instance through the Google Cloud Platform Console, select the following values in the Identity and API access section of the Create an instance panel:

  1. Select Compute Engine default service account for Service account
  2. Select Allow full access to all Cloud APIs for Access Scopes

To use something other than the Compute Engine default service account see the Creating and enabling service accounts for instances and Running locally and elsewhere sections. The important thing is that the service account you use has the Cloud Trace Agent role.

Running locally and elsewhere

To run Stackdriver Trace outside of GCP you must supply your GCP project ID and appropriate service account credentials directly to Stackdriver Trace library for Node.js. Your service account must contain the Cloud Trace agent role. For instructions, see Creating a service account.

Project ID

Provide a project ID to the Stackdriver Trace library for Node.js by setting the projectId value in the options object passed to the library's start method, or set the GCLOUD_PROJECT environment variable:

Linux or macOS

export GCLOUD_PROJECT=your-project-id

Windows

set GCLOUD_PROJECT=your-project-id

PowerShell:

$env:GCLOUD_PROJECT="your-project-id"

Credentials

GCP client libraries use Application default credentials (ADC) to find your application's credentials. You provide credentials to the Stackdriver Trace library for Node.js by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable:

Linux/macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"

Example

require('@google-cloud/trace-agent').start({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json'
});

Sample application

if (process.env.NODE_ENV === 'production') {
  require('@google-cloud/trace-agent').start();
}

const express = require('express');
const got = require('got');

const app = express();
const DISCOVERY_URL = 'https://www.googleapis.com/discovery/v1/apis';

// This incoming HTTP request should be captured by Trace
app.get('/', async (req, res) => {
  // This outgoing HTTP request should be captured by Trace
  try {
    const { body } = await got(DISCOVERY_URL, { json: true });
    const names = body.items.map((item) => item.name);
    res
      .status(200)
      .send(names.join('\n'))
      .end();
  }
  catch (err) {
    console.error(err);
    res
      .status(500)
      .end();
  }
});

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

Viewing the traces

After deployment, you can view the traces in the GCP Console Trace Viewer.

Go to the Trace Viewer page

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

Send feedback about...

Stackdriver Trace
Need help? Visit our support page.