Protobuf.js

8.0.1 · active · verified Sun Apr 19

Protobuf.js is a comprehensive JavaScript and TypeScript implementation of Protocol Buffers, providing tools for encoding and decoding structured data efficiently. It supports both dynamic (reflection-based) parsing of .proto schemas and static code generation for optimized performance and type safety. The library is actively maintained, with the current stable version being 8.0.1 as of early 2026, and frequent updates addressing bugs and security concerns, alongside less frequent major releases that introduce new features and breaking changes. Protobuf.js aims to be versatile, usable in both Node.js environments and browsers, making it a robust choice for projects requiring high-performance data serialization across different JavaScript runtimes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically define a simple Protobuf schema using `Root`, `Type`, and `Field`. It then shows the complete flow of creating a message payload, verifying it, encoding it into a binary buffer, and subsequently decoding the buffer back into a JavaScript object, illustrating core serialization capabilities.

import { Root, Type, Field } from 'protobufjs';

// 1. Define a .proto schema programmatically
const root = new Root('my_schema_root');
const MyMessage = new Type('MyMessage')
  .add(new Field('name', 1, 'string'))
  .add(new Field('id', 2, 'int32'))
  .add(new Field('isActive', 3, 'bool'));

root.add(MyMessage);

// In a typical application, you'd load from a .proto file:
// import { loadSync } from 'protobufjs';
// import { join } from 'node:path';
// const rootFromFile = loadSync(join(__dirname, 'my_service.proto'));
// const MyMessageFromRoot = rootFromFile.lookupType('MyMessage');

// 2. Prepare data to be encoded
const payload = {
  name: 'Jane Doe',
  id: 123,
  isActive: true
};

// 3. Verify the payload against the schema (optional, but good for debugging)
const errMsg = MyMessage.verify(payload);
if (errMsg) {
  throw new Error(`Invalid payload: ${errMsg}`);
}

// 4. Create a message instance and encode it to a buffer
const message = MyMessage.create(payload);
const buffer = MyMessage.encode(message).finish();

console.log('Encoded buffer (hex):', buffer.toString('hex'));

// 5. Decode the buffer back into a message object
const decodedMessage = MyMessage.decode(buffer);

console.log('Decoded message:', JSON.stringify(decodedMessage.toJSON()));

// Example: decoding a message with missing fields (will use default values)
const partialBuffer = MyMessage.encode(MyMessage.create({ name: 'Partial Test' })).finish();
const decodedPartial = MyMessage.decode(partialBuffer);
console.log('Decoded partial message (id and isActive default):', JSON.stringify(decodedPartial.toJSON()));

view raw JSON →