The default export of the @google-cloud/pubsub package is the PubSub class.

See PubSub and ClientConfig for client methods and configuration options.


Install the client library with npm:

npm install @google-cloud/pubsub

Import the client library

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

Create a client that uses Application Default Credentials (ADC):

const pubsub = new PubSub();

Create a client with explicit credentials:

const pubsub = new PubSub({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'

Full quickstart example:

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

async function quickstart(
  projectId = 'your-project-id', // Your Google Cloud Platform project ID
  topicName = 'my-topic', // Name for the new topic to create
  subscriptionName = 'my-sub' // Name for the new subscription to create
) {
  // Instantiates a client
  const pubsub = new PubSub({projectId});

  // Creates a new topic
  const [topic] = await pubsub.createTopic(topicName);
  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());

  // Receive callbacks for errors on the subscription
  subscription.on('error', error => {
    console.error('Received error:', error);

  // Send a message to the topic
  topic.publish(Buffer.from('Test message!'));



Reference to internal generated clients, advanced use only.

Name Type Description
PublisherClient constructor

Reference to v1.PublisherClient.

SubscriberClient constructor

Reference to v1.SubscriberClient.