Class PubSub (4.8.0) Stay organized with collections Save and categorize content based on your preferences.
[Cloud Pub/Sub](https://developers.google.com/pubsub/overview) is a reliable, many-to-many, asynchronous messaging service from Cloud Platform.
Package
@google-cloud/pubsubExamples
Import the client library
const{PubSub}=require('@google-cloud/pubsub');Create a client that usesApplication Default Credentials (ADC):
constpubsub=newPubSub();Create a client withexplicit credentials:
constpubsub=newPubSub({projectId:'your-project-id',keyFilename:'/path/to/keyfile.json'});Full quickstart example:
// Imports the Google Cloud client libraryimport{PubSub}from'@google-cloud/pubsub';asyncfunctionquickstart(projectId='your-project-id',// Your Google Cloud Platform project IDtopicNameOrId='my-topic',// Name for the new topic to createsubscriptionName='my-sub'// Name for the new subscription to create){// Instantiates a clientconstpubsub=newPubSub({projectId});// Creates a new topicconst[topic]=awaitpubsub.createTopic(topicNameOrId);console.log(`Topic${topic.name} created.`);// Creates a subscription on that new topicconst[subscription]=awaittopic.createSubscription(subscriptionName);// Receive callbacks for new messages on the subscriptionsubscription.on('message',message=>{console.log('Received message:',message.data.toString());process.exit(0);});// Receive callbacks for errors on the subscriptionsubscription.on('error',error=>{console.error('Received error:',error);process.exit(1);});// Send a message to the topictopic.publishMessage({data:Buffer.from('Test message!')});}Constructors
(constructor)(options)
constructor(options?:ClientConfig);Constructs a new instance of thePubSub class
| Parameter | |
|---|---|
| Name | Description |
options | ClientConfig |
Properties
api
api:{[key:string]:gax.ClientStub;};auth
auth:GoogleAuth;getSnapshotsStream
getSnapshotsStream:()=>ObjectStream<Snapshot>;getSubscriptionsStream
getSubscriptionsStream:()=>ObjectStream<Subscription>;getTopicsStream
getTopicsStream:()=>ObjectStream<Topic>;isEmulator
isEmulator:boolean;isIdResolved
getisIdResolved():boolean;Returns true if we have actually resolved the full project name.
isOpen
isOpen:boolean;name
name?:string;options
options:ClientConfig;projectId
projectId:string;Promise
Promise?:PromiseConstructor;Methods
close()
close():Promise<void>;Closes out this object, releasing any server connections. Note that once you close a PubSub object, it may not be used again. Any pending operations (e.g. queued publish messages) will fail. If you have topic or subscription objects that may have pending operations, you should call close() on those first if you want any pending messages to be delivered correctly. The PubSub class doesn't track those.
EmptyCallback
| Returns | |
|---|---|
| Type | Description |
Promise<void> | {Promise |
close(callback)
close(callback:EmptyCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | EmptyCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
closeAllClients_()
closeAllClients_():Promise<void>;Close all open client objects.
| Returns | |
|---|---|
| Type | Description |
Promise<void> | {Promise} |
createSchema(schemaId, type, definition, gaxOpts)
createSchema(schemaId:string,type:SchemaType,definition:string,gaxOpts?:CallOptions):Promise<Schema>;Create a schema in the project.
| Parameters | |
|---|---|
| Name | Description |
schemaId | stringThe name or ID of the subscription. |
type | SchemaTypeThe type of the schema (Protobuf, Avro, etc). |
definition | stringThe text describing the schema in terms of the type. |
gaxOpts | CallOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<Schema> | {Promise |
Create a schema.
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();awaitpubsub.createSchema('messageType',SchemaTypes.Avro,'{...avro definition...}');createSubscription(topic, name, options)
createSubscription(topic:Topic|string,name:string,options?:CreateSubscriptionOptions):Promise<CreateSubscriptionResponse>;Create a subscription to a topic.
| Parameters | |
|---|---|
| Name | Description |
topic | Topic | stringThe Topic to create a subscription to. |
name | stringThe name of the subscription. |
options | CreateSubscriptionOptionsSee a [Subscription resource](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions). |
| Returns | |
|---|---|
| Type | Description |
Promise<CreateSubscriptionResponse> | {Promise |
Subscribe to a topic.
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();consttopic='messageCenter';constname='newMessages';constcallback=function(err,subscription,apiResponse){};pubsub.createSubscription(topic,name,callback);If the callback is omitted, we'll return a Promise.
pubsub.createSubscription(topic,name).then(function(data){constsubscription=data[0];constapiResponse=data[1];});createSubscription(topic, name, callback)
createSubscription(topic:Topic|string,name:string,callback:CreateSubscriptionCallback):void;| Parameters | |
|---|---|
| Name | Description |
topic | Topic | string |
name | string |
callback | CreateSubscriptionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
createSubscription(topic, name, options, callback)
createSubscription(topic:Topic|string,name:string,options:CreateSubscriptionOptions,callback:CreateSubscriptionCallback):void;| Parameters | |
|---|---|
| Name | Description |
topic | Topic | string |
name | string |
options | CreateSubscriptionOptions |
callback | CreateSubscriptionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
createTopic(name, gaxOpts)
createTopic(name:string|TopicMetadata,gaxOpts?:CallOptions):Promise<CreateTopicResponse>;Create a topic with the given name.
| Parameters | |
|---|---|
| Name | Description |
name | string |TopicMetadataName of the topic. |
gaxOpts | CallOptionsRequest configuration options, outlined here:https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html. |
| Returns | |
|---|---|
| Type | Description |
Promise<CreateTopicResponse> | {Promise |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();pubsub.createTopic('my-new-topic',function(err,topic,apiResponse){if(!err){// The topic was created successfully.}});//-// If the callback is omitted, we'll return a Promise.//-pubsub.createTopic('my-new-topic').then(function(data){consttopic=data[0];constapiResponse=data[1];});createTopic(name, callback)
createTopic(name:string|TopicMetadata,callback:CreateTopicCallback):void;| Parameters | |
|---|---|
| Name | Description |
name | string |TopicMetadata |
callback | CreateTopicCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
createTopic(name, gaxOpts, callback)
createTopic(name:string|TopicMetadata,gaxOpts:CallOptions,callback:CreateTopicCallback):void;| Parameters | |
|---|---|
| Name | Description |
name | string |TopicMetadata |
gaxOpts | CallOptions |
callback | CreateTopicCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
detachSubscription(name, gaxOpts)
detachSubscription(name:string,gaxOpts?:CallOptions):Promise<DetachSubscriptionResponse>;Detach a subscription with the given name.
| Parameters | |
|---|---|
| Name | Description |
name | stringName of the subscription. |
gaxOpts | CallOptionsRequest configuration options, outlined here:https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html. |
| Returns | |
|---|---|
| Type | Description |
Promise<DetachSubscriptionResponse> | {Promise |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();pubsub.detachSubscription('my-sub',(err,topic,apiResponse)=>{if(!err){// The topic was created successfully.}});//-// If the callback is omitted, we'll return a Promise.//-pubsub.detachSubscription('my-sub').then(data=>{constapiResponse=data[0];});detachSubscription(name, callback)
detachSubscription(name:string,callback:DetachSubscriptionCallback):void;| Parameters | |
|---|---|
| Name | Description |
name | string |
callback | DetachSubscriptionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
detachSubscription(name, gaxOpts, callback)
detachSubscription(name:string,gaxOpts:CallOptions,callback:DetachSubscriptionCallback):void;| Parameters | |
|---|---|
| Name | Description |
name | string |
gaxOpts | CallOptions |
callback | DetachSubscriptionCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
determineBaseUrl_()
determineBaseUrl_():void;Determine the appropriate endpoint to use for API requests, first trying theapiEndpoint parameter. If that isn't set, we try the Pub/Sub emulator environment variable (PUBSUB_EMULATOR_HOST). If that is also null, we try the standardgcloud alpha pubsub environment variable (CLOUDSDK_API_ENDPOINT_OVERRIDES_PUBSUB). Otherwise the default production API is used.
Note that if the URL doesn't end in '.googleapis.com', we will assume that it's an emulator and disable strict SSL checks.
| Returns | |
|---|---|
| Type | Description |
void | |
formatName_(name)
staticformatName_(name:string):string;| Parameter | |
|---|---|
| Name | Description |
name | string |
| Returns | |
|---|---|
| Type | Description |
string | |
getClient_(config, callback)
getClient_(config:GetClientConfig,callback:GetClientCallback):void;Get the PubSub client object.
| Parameters | |
|---|---|
| Name | Description |
config | GetClientConfigConfiguration object. |
callback | GetClientCallbackThe callback function. |
| Returns | |
|---|---|
| Type | Description |
void | |
getClientAsync_(config)
getClientAsync_(config:GetClientConfig):Promise<gax.ClientStub>;Get the PubSub client object.
| Parameter | |
|---|---|
| Name | Description |
config | GetClientConfigConfiguration object. |
| Returns | |
|---|---|
| Type | Description |
Promise<ClientStub> | {Promise} |
getClientConfig()
getClientConfig():Promise<ClientConfig>;Retrieve a client configuration, suitable for passing into a GAPIC 'v1' class constructor. This will fill out projectId, emulator URLs, and so forth.
| Returns | |
|---|---|
| Type | Description |
Promise<ClientConfig> | {Promise |
getSchemaClient()
getSchemaClient():Promise<SchemaServiceClient>;Gets a schema client, creating one if needed. This is a shortcut fornew v1.SchemaServiceClient(await pubsub.getClientConfig()).
| Returns | |
|---|---|
| Type | Description |
Promise<SchemaServiceClient> | {Promise |
getSnapshots(options)
getSnapshots(options?:PageOptions):Promise<GetSnapshotsResponse>;Get a list of snapshots.
| Parameter | |
|---|---|
| Name | Description |
options | PageOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<GetSnapshotsResponse> | {Promise |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();pubsub.getSnapshots(function(err,snapshots){if(!err){// snapshots is an array of Snapshot objects.}});//-// If the callback is omitted, we'll return a Promise.//-pubsub.getSnapshots().then(function(data){constsnapshots=data[0];});getSnapshots(callback)
getSnapshots(callback:GetSnapshotsCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | GetSnapshotsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getSnapshots(options, callback)
getSnapshots(options:PageOptions,callback:GetSnapshotsCallback):void;| Parameters | |
|---|---|
| Name | Description |
options | PageOptions |
callback | GetSnapshotsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getSubscriptions(options)
getSubscriptions(options?:GetSubscriptionsOptions):Promise<GetSubscriptionsResponse>;Get a list of the subscriptions registered to all of your project's topics. You may optionally provide a query object as the first argument to customize the response.
Your provided callback will be invoked with an error object if an API error occurred or an array of objects.
To get subscriptions for a topic, seeTopic.
| Parameter | |
|---|---|
| Name | Description |
options | GetSubscriptionsOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<GetSubscriptionsResponse> | {Promise |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();pubsub.getSubscriptions(function(err,subscriptions){if(!err){// subscriptions is an array of Subscription objects.}});//-// If the callback is omitted, we'll return a Promise.//-pubsub.getSubscriptions().then(function(data){constsubscriptions=data[0];});getSubscriptions(callback)
getSubscriptions(callback:GetSubscriptionsCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | GetSubscriptionsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getSubscriptions(options, callback)
getSubscriptions(options:GetSubscriptionsOptions,callback:GetSubscriptionsCallback):void;| Parameters | |
|---|---|
| Name | Description |
options | GetSubscriptionsOptions |
callback | GetSubscriptionsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getTopics(options)
getTopics(options?:PageOptions):Promise<GetTopicsResponse>;Get a list of the topics registered to your project. You may optionally provide a query object as the first argument to customize the response.
| Parameter | |
|---|---|
| Name | Description |
options | PageOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<GetTopicsResponse> | {Promise |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();pubsub.getTopics(function(err,topics){if(!err){// topics is an array of Topic objects.}});//-// Customize the query.//-pubsub.getTopics({pageSize:3},function(err,topics){});//-// If the callback is omitted, we'll return a Promise.//-pubsub.getTopics().then(function(data){consttopics=data[0];});getTopics(callback)
getTopics(callback:GetTopicsCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | GetTopicsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getTopics(options, callback)
getTopics(options:PageOptions,callback:GetTopicsCallback):void;| Parameters | |
|---|---|
| Name | Description |
options | PageOptions |
callback | GetTopicsCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
listSchemas(view, options)
listSchemas(view?:SchemaView,options?:CallOptions):AsyncIterable<google.pubsub.v1.ISchema>;Get a list of schemas associated with your project.
The returned AsyncIterable will resolve to objects.
This method returns an async iterable. These objects can be adapted to work in a Promise/then framework, as well as with callbacks, but this discussion is considered out of scope for these docs.
| Parameters | |
|---|---|
| Name | Description |
view | SchemaViewThe type of schema objects requested, which should be an enum value fromSchemaViews. Defaults to Full. |
options | CallOptionsRequest configuration options, outlined here:https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html. |
| Returns | |
|---|---|
| Type | Description |
AsyncIterable<google.pubsub.v1.ISchema> | {AsyncIterable |
forawait(constsofpubsub.listSchemas()){constmoreInfo=awaits.get();}request(config, callback)
request<T,R=void>(config:RequestConfig,callback:RequestCallback<T,R>):void;Funnel all API requests through this method, to be sure we have a project ID.
| Parameters | |
|---|---|
| Name | Description |
config | RequestConfigConfiguration object. |
callback | RequestCallback<T, R>The callback function. |
| Returns | |
|---|---|
| Type | Description |
void | |
| Type Parameters | |
|---|---|
| Name | Description |
T | |
R | |
schema(idOrName)
schema(idOrName:string):Schema;Create a Schema object, representing a schema within the project. See or to create a schema.
| Parameter | |
|---|---|
| Name | Description |
idOrName | string |
| Returns | |
|---|---|
| Type | Description |
Schema | {Schema} ASchema instance. |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();constschema=pubsub.schema('my-schema');snapshot(name)
snapshot(name:string):Snapshot;Create a Snapshot object. See to create a snapshot.
| Parameter | |
|---|---|
| Name | Description |
name | stringThe name of the snapshot. |
| Returns | |
|---|---|
| Type | Description |
Snapshot | {Snapshot} ASnapshot instance. |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();constsnapshot=pubsub.snapshot('my-snapshot');subscription(name, options)
subscription(name:string,options?:SubscriptionOptions):Subscription;Create a Subscription object. This command by itself will not run any API requests. You will receive a object, which will allow you to interact with a subscription.
| Parameters | |
|---|---|
| Name | Description |
name | stringName of the subscription. |
options | SubscriptionOptionsConfiguration object. |
| Returns | |
|---|---|
| Type | Description |
Subscription | {Subscription} A instance. |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();constsubscription=pubsub.subscription('my-subscription');// Register a listener for `message` events.subscription.on('message',function(message){// Called every time a message is received.// message.id = ID of the message.// message.ackId = ID used to acknowledge the message receival.// message.data = Contents of the message.// message.attributes = Attributes of the message.// message.publishTime = Date when Pub/Sub received the message.});topic(name, options)
topic(name:string,options?:PublishOptions):Topic;Create a Topic object. See to create a topic.
| Parameters | |
|---|---|
| Name | Description |
name | stringThe name of the topic. |
options | PublishOptionsPublisher configuration object. |
| Returns | |
|---|---|
| Type | Description |
Topic | {Topic} ATopic instance. |
const{PubSub}=require('@google-cloud/pubsub');constpubsub=newPubSub();consttopic=pubsub.topic('my-topic');validateSchema(schema, gaxOpts)
validateSchema(schema:ISchema,gaxOpts?:CallOptions):Promise<void>;Validate a schema definition.
| Parameters | |
|---|---|
| Name | Description |
schema | ISchemaThe schema definition you wish to validate. |
gaxOpts | CallOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<void> | {Promise |
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.