Google Cloud Pub/Sub: Node.js Client

release levelnpm version

Cloud Pub/Sub is a fully-managed real-time messaging service that allowsyou to send and receive messages between independent applications.

This document contains links to anAPI reference, samples,and other resources useful to developing Node.js applications.For additional help developing Pub/Sub applications, in Node.js and other languages, see ourPub/Sub quickstart,publisher, andsubscriberguides.

A comprehensive list of changes in each version may be found inthe CHANGELOG.

Read more about the client libraries for Cloud APIs, including the olderGoogle APIs Client Libraries, inClient Libraries Explained.

Table of contents:

Quickstart

Before you begin

  1. Select or create a Cloud Platform project.
  2. Enable billing for your project.
  3. Enable the Google Cloud Pub/Sub API.
  4. Set up authentication with a service account so you can access theAPI from your local workstation.

Installing the client library

npm install @google-cloud/pubsub

Using the client library

// Imports the Google Cloud client libraryconst {PubSub} = require('@google-cloud/pubsub');async function quickstart(  projectId = 'your-project-id', // Your Google Cloud Platform project ID  topicNameOrId = 'my-topic', // Name for the new topic to create  subscriptionName = 'my-sub' // Name for the new subscription to create) {  // Instantiates a client  const pubsub = newPubSub({projectId});  // Creates a new topic  const [topic] = await pubsub.createTopic(topicNameOrId);  console.log(`Topic ${topic.name} created.`);  // Creates a subscription on that new topic  const [subscription] = await topic.createSubscription(subscriptionName);  // Receive callbacks for new messages on the subscription  subscription.on('message', message => {    console.log('Received message:', message.data.toString());    process.exit(0);  });  // Receive callbacks for errors on the subscription  subscription.on('error', error => {    console.error('Received error:', error);    process.exit(1);  });  // Send a message to the topic  topic.publishMessage({data: Buffer.from('Test message!')});}

Running gRPC C++ bindings

For some workflows and environments it might make sense to use the C++ gRPC implementation,instead of the default one (see:#770):

To configure@google-cloud/pubsub to use an alternativegrpc transport:

  1. npm install grpc, addinggrpc as a dependency.
  2. instantiate@google-cloud/pubsub withgrpc:

    const {PubSub} = require('@google-cloud/pubsub');const grpc = require('grpc');const pubsub = newPubSub({grpc});

Samples

Samples are in thesamples/ directory. Each sample'sREADME.md has instructions for running its sample.

SampleSource CodeTry it
Create an Avro based Schemasource codeOpen in Cloud Shell
Create BigQuery Subscriptionsource codeOpen in Cloud Shell
Create a Proto based Schemasource codeOpen in Cloud Shell
Create Push Subscriptionsource codeOpen in Cloud Shell
Create Subscriptionsource codeOpen in Cloud Shell
Create Subscription With Dead Letter Policysource codeOpen in Cloud Shell
Create an exactly-once delivery subscriptionsource codeOpen in Cloud Shell
Create Subscription With Filteringsource codeOpen in Cloud Shell
Create Subscription with ordering enabledsource codeOpen in Cloud Shell
Create Subscription With Retry Policysource codeOpen in Cloud Shell
Create Topicsource codeOpen in Cloud Shell
Create Topic With Schemasource codeOpen in Cloud Shell
Delete a previously created schemasource codeOpen in Cloud Shell
Delete Subscriptionsource codeOpen in Cloud Shell
Delete Topicsource codeOpen in Cloud Shell
Detach Subscriptionsource codeOpen in Cloud Shell
Get a previously created schemasource codeOpen in Cloud Shell
Get Subscriptionsource codeOpen in Cloud Shell
Get Subscription Policysource codeOpen in Cloud Shell
Get Topic Policysource codeOpen in Cloud Shell
List All Topicssource codeOpen in Cloud Shell
List schemas on a projectsource codeOpen in Cloud Shell
List Subscriptionssource codeOpen in Cloud Shell
List Subscriptions On a Topicsource codeOpen in Cloud Shell
Listen For Avro Recordssource codeOpen in Cloud Shell
Listen For Errorssource codeOpen in Cloud Shell
Listen For Messagessource codeOpen in Cloud Shell
Listen with exactly-once deliverysource codeOpen in Cloud Shell
Listen For Protobuf Messagessource codeOpen in Cloud Shell
Listen For Messages With Custom Attributessource codeOpen in Cloud Shell
Modify Push Configurationsource codeOpen in Cloud Shell
OpenTelemetry Tracingsource codeOpen in Cloud Shell
Publish Avro Records to a Topicsource codeOpen in Cloud Shell
Publish Batched Messagessource codeOpen in Cloud Shell
Publish Messagesource codeOpen in Cloud Shell
Publish Message With Custom Attributessource codeOpen in Cloud Shell
Publish Ordered Messagesource codeOpen in Cloud Shell
Publish Protobuf Messages to a Topicsource codeOpen in Cloud Shell
Publish with flow controlsource codeOpen in Cloud Shell
Publish With Retry Settingssource codeOpen in Cloud Shell
Quickstartsource codeOpen in Cloud Shell
Remove Dead Letter Policysource codeOpen in Cloud Shell
Resume Publishsource codeOpen in Cloud Shell
Set Subscription IAM Policysource codeOpen in Cloud Shell
Set Topic IAM Policysource codeOpen in Cloud Shell
Subscribe With Flow Control Settingssource codeOpen in Cloud Shell
Synchronous Pullsource codeOpen in Cloud Shell
Synchronous Pull with delivery attempt.source codeOpen in Cloud Shell
Synchronous Pull With Lease Managementsource codeOpen in Cloud Shell
Test Subscription Permissionssource codeOpen in Cloud Shell
Test Topic Permissionssource codeOpen in Cloud Shell
Update Dead Letter Policysource codeOpen in Cloud Shell
Validate a schema definitionsource codeOpen in Cloud Shell

TheGoogle Cloud Pub/Sub Node.js Client API Reference documentationalso contains samples.

Supported Node.js Versions

Our client libraries follow theNode.js release schedule.Libraries are compatible with all currentactive andmaintenance versions ofNode.js.If you are using an end-of-life version of Node.js, we recommend that you updateas soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on abest-efforts basis with the following warnings:

  • Legacy versions are not tested in continuous integration.
  • Some security patches and features cannot be backported.
  • Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, andcan be installed through npmdist-tags.The dist-tags follow the naming conventionlegacy-(version).For example,npm install @google-cloud/pubsub@legacy-8 installs client librariesfor versions compatible with Node.js 8.

Versioning

This library followsSemantic Versioning.

This library is considered to bestable. The code surface will not change in backwards-incompatible waysunless absolutely necessary (e.g. because of critical security issues) or withan extensive deprecation period. Issues and requests againststable librariesare addressed with the highest priority.

More Information:Google Cloud Platform Launch Stages

Contributing

Contributions welcome! See theContributing Guide.

Please note that thisREADME.md, thesamples/README.md,and a variety of configuration files in this repository (including.nycrc andtsconfig.json)are generated from a central template. To edit one of these files, make an editto its templates indirectory.

License

Apache Version 2.0

SeeLICENSE

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.