Google Protocol Buffers for JavaScript
Protocol Buffers for JavaScript provides the runtime library for Google's efficient, language-agnostic, and extensible mechanism for serializing structured data. The current stable version is 4.0.2, with releases generally tied to upstream `protoc` compiler updates and critical bug fixes, focusing on maintaining compatibility. This package primarily serves as the runtime component, which is internally consumed by JavaScript files generated from `.proto` definitions using the `protoc` compiler and its `protoc-gen-js` plugin. It explicitly supports CommonJS-style and Closure-style imports for the generated code, but direct ES6 module support for these generated `.js` files is not yet implemented, often necessitating build tools like Webpack or Browserify for seamless browser integration. A key differentiator is its deep integration with the broader Protocol Buffers ecosystem, offering a robust and standardized solution for defining and exchanging structured data across different programming languages in JavaScript and Node.js applications.
Common errors
-
Error: Cannot find module './my_proto_pb'
cause Attempting to `require()` a generated `.proto` file (e.g., `my_proto_pb.js`) that has not been created, or the path is incorrect.fixEnsure you have successfully compiled your `.proto` file using `protoc` with the correct output directory (e.g., `protoc --js_out=import_style=commonjs,binary:. my_proto.proto`). Verify the path in your `require()` statement matches the generated file's location. -
protoc: command not found
cause The Protocol Compiler (`protoc`) is not installed or not accessible in your system's PATH.fixDownload and install `protoc` from the official Protocol Buffers GitHub releases page (https://github.com/protocolbuffers/protobuf/releases) and ensure its directory is added to your system's PATH environment variable. -
plugin was not found: protoc-gen-js
cause The `protoc-gen-js` plugin, which translates `.proto` files to JavaScript, is not installed or `protoc` cannot find it.fixInstall the plugin via npm (`npm install @protocolbuffers/protoc-gen-js`) and ensure you pass the `--plugin` argument to `protoc`, specifying the full path to `cli.js` (e.g., `--plugin=protoc-gen-js=$(npm root)/@protocolbuffers/protoc-gen-js/cli.js`).
Warnings
- breaking Version 4.0.0 introduced significant breaking changes, including changes to binary proto serialization/deserialization, enabling Protobuf Editions 2023, fixes for JSPB binary UTF-8 decoding (validated by default), and limiting global resolution to `globalThis`.
- gotcha The generated JavaScript files (e.g., `_pb.js`) do not natively support ES6-style `import` statements. They are designed for CommonJS `require()` or Closure `goog.require()`. Attempting to use `import` directly for generated files will result in module resolution errors.
- gotcha The `@protocolbuffers/protoc-gen-js` plugin was temporarily hardcoded to download version 4.0.0, lacking support for Editions 2024, leading to compilation issues for newer `.proto` definitions. This was fixed in `google-protobuf` v4.0.2.
- gotcha Early releases of v4.0.2 had issues with macOS and Windows binaries for `protoc-gen-js` being double-zipped, causing download script failures within `@protocolbuffers/protoc-gen-js`.
- gotcha The project explicitly states that it has 'minimal support for this open source project', with limited staffing to answer questions beyond triage. This indicates slower response times for issues and feature requests.
Install
-
npm install google-protobuf -
yarn add google-protobuf -
pnpm add google-protobuf
Imports
- MyMessage
import { MyMessage } from './my_proto_pb';const { MyMessage } = require('./my_proto_pb'); - Timestamp
import { Timestamp } => from 'google-protobuf/google/protobuf/timestamp_pb';const { Timestamp } = require('google-protobuf/google/protobuf/timestamp_pb'); - jspb
import jspb from 'google-protobuf/google/protobuf/jspb/jspb.js';
const jspb = require('google-protobuf/google/protobuf/jspb/jspb.js');
Quickstart
/*
First, ensure you have the `protoc` compiler installed and on your PATH.
Download a pre-built binary from https://github.com/protocolbuffers/protobuf/releases
Then install the necessary npm packages:
npm install google-protobuf @protocolbuffers/protoc-gen-js
Create a file named `example.proto`:
*/
// example.proto
/*
syntax = "proto3";
package mypackage;
message MyMessage {
string name = 1;
int32 id = 2;
repeated string tags = 3;
}
*/
/*
Compile your .proto file using protoc:
protoc --js_out=import_style=commonjs,binary:. example.proto \
--plugin=protoc-gen-js=$(npm root)/@protocolbuffers/protoc-gen-js/cli.js
This will generate `example_pb.js`.
Now, run this JavaScript code (e.g., `node quickstart.js`):
*/
const { MyMessage } = require('./example_pb'); // Import the generated message class
const { Timestamp } = require('google-protobuf/google/protobuf/timestamp_pb'); // Import a well-known type
// Create a new instance of MyMessage
const message = new MyMessage();
message.setName('Hello Protobuf World');
message.setId(42);
message.addTags('example');
message.addTags('typescript');
console.log('Original Message:', message.toObject());
// Serialize the message to a binary buffer
const binaryData = message.serializeBinary();
console.log('Serialized Binary Data:', binaryData);
// Deserialize the message from the binary buffer
const deserializedMessage = MyMessage.deserializeBinary(binaryData);
console.log('Deserialized Message Name:', deserializedMessage.getName());
console.log('Deserialized Message ID:', deserializedMessage.getId());
console.log('Deserialized Message Tags:', deserializedMessage.getTagsList());
// Demonstrate using a Timestamp well-known type
const now = new Date();
const timestamp = new Timestamp();
timestamp.fromDate(now); // Convert a JavaScript Date object to a Protobuf Timestamp
console.log('Current Timestamp (Protobuf format):', timestamp.toObject());