Protocol Buffers
suggest changeProtocol Buffers (protobuf) is Google's language-neutral format for structured data. You describe your messages in a .proto schema file, and a library for each language encodes and decodes them to a compact binary form. Fields are identified by numbers instead of names, which is why the encoding is small and why old and new versions of a program can read each other's data.
Protobuf is a good fit when:
- services written in different languages exchange data (it's the payload format of gRPC)
- you want a schema that documents the data and catches type errors
- message size or parsing speed matters more than human readability
- data written today must still be readable after the schema changes
Node.js has no built-in protobuf support. The two widely used packages are:
| Package | Schema handling | 64-bit integers | Notes |
|---|---|---|---|
protobufjs |
loads .proto at runtime, or generates code with pbjs |
Long objects, converts to bigint/string |
no protoc needed, reflection API |
@bufbuild/protobuf (Protobuf-ES) |
generated code only (buf generate or protoc) |
bigint |
plain objects, TypeScript-first, full ProtoJSON |
For a general comparison of JSON, v8.serialize, MessagePack and other formats see Object serialization.
The examples were run with Node.js 24, protobufjs 8.8, protobufjs-cli 2.7, @bufbuild/protobuf 2.16 and @bufbuild/buf 1.74. The project's package.json has "type": "module".
The schema
Most examples use this file, saved as proto/shop.proto:
syntax = "proto3";
package shop;
enum Status {
STATUS_UNSPECIFIED = 0;
STATUS_PENDING = 1;
STATUS_PAID = 2;
STATUS_SHIPPED = 3;
}
message Item {
string sku = 1;
uint32 quantity = 2;
int64 price_cents = 3;
}
message Order {
uint64 id = 1;
string customer = 2;
Status status = 3;
repeated Item items = 4;
map<string, string> metadata = 5;
optional string note = 6;
oneof payment {
string card_last4 = 7;
string iban = 8;
}
}
Things to note:
- the number after each field (
= 1,= 2) is the field's identity on the wire. The name is only used by generated code and the JSON form. Once data is out there, never change a field's number. - the first enum value must be zero. It's the default, so make it a "not set" value rather than a real state.
repeatedis a list,map<K, V>a dictionary,oneofa group of fields of which at most one is setoptionalturns on presence tracking for a scalar field, so you can tell "set to empty string" from "not set"int64anduint64can hold values beyondNumber.MAX_SAFE_INTEGER, so libraries don't return them as plain numbers
Encoding and decoding with protobufjs
Install it with npm install protobufjs. protobuf.load() parses the .proto file at runtime and lookupType() returns a reflected message type:
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Order = root.lookupType('shop.Order');
const Status = root.lookupEnum('shop.Status');
const order = {
id: 1001,
customer: 'alice',
status: Status.values.STATUS_PAID,
items: [
{ sku: 'A-100', quantity: 2, priceCents: 1990 },
{ sku: 'B-200', quantity: 1, priceCents: 550 },
],
metadata: { source: 'web' },
cardLast4: '4242',
};
const err = Order.verify(order);
if (err) throw new Error(err);
const bytes = Order.encode(order).finish();
console.log(bytes.constructor.name, bytes.length, 'bytes');
console.log('JSON:', Buffer.byteLength(JSON.stringify(order)), 'bytes');
const decoded = Order.decode(bytes);
console.log(decoded);
console.log(decoded instanceof Order.ctor);
console.log(decoded.id, typeof decoded.id);
console.log(decoded.payment);
Buffer 61 bytes
JSON: 191 bytes
Message {
items: [
Message { sku: 'A-100', quantity: 2, priceCents: [Long] },
Message { sku: 'B-200', quantity: 1, priceCents: [Long] }
],
metadata: { source: 'web' },
id: Long { low: 1001, high: 0, unsigned: true },
customer: 'alice',
status: 2,
cardLast4: '4242'
}
true
Long { low: 1001, high: 0, unsigned: true } object
cardLast4
How it works:
- field names are converted to camelCase:
price_centsbecomespriceCents. Pass{ keepCase: true }toload()to keep the names as written. encode()returns aWriter, andfinish()gives the bytes. In Node.js that's aBuffer.decode()returns a message instance. 64-bit fields come back asLongobjects (from thelongpackage) because a JavaScript number can't hold every 64-bit value.- enums are plain numbers on the message.
Status.valuesmaps names to numbers andStatus.valuesByIdmaps numbers to names. - for a
oneof, the virtual propertydecoded.paymentholds the name of the field that is set
The binary form is a third of the size of the JSON. Most of the saving comes from not repeating field names in every message.
protobuf.loadSync() does the same synchronously, which is handy at startup or in scripts.
Getting plain objects back
toObject() converts a message to a plain object and lets you pick how 64-bit integers, enums and bytes are represented:
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Order = root.lookupType('shop.Order');
const bytes = Order.encode({
id: 1001,
customer: 'alice',
status: 2,
items: [{ sku: 'A-100', quantity: 2, priceCents: 1990 }],
cardLast4: '4242',
}).finish();
const msg = Order.decode(bytes);
console.log(Order.toObject(msg, {
longs: String,
enums: String,
oneofs: true,
}));
console.log(Order.toObject(msg, {
longs: Number,
enums: String,
defaults: true,
}));
console.log(JSON.stringify(msg));
console.log(Order.toObject(msg, { longs: BigInt }).id);
{
id: '1001',
customer: 'alice',
status: 'STATUS_PAID',
items: [ { sku: 'A-100', quantity: 2, priceCents: '1990' } ],
cardLast4: '4242',
payment: 'cardLast4'
}
{
items: [ { sku: 'A-100', quantity: 2, priceCents: 1990 } ],
metadata: {},
id: 1001,
customer: 'alice',
status: 'STATUS_PAID',
cardLast4: '4242'
}
{"id":"1001","customer":"alice","status":"STATUS_PAID","items":[{"sku":"A-100","quantity":2,"priceCents":"1990"}],"cardLast4":"4242"}
1001n
The options:
| Option | Effect |
|---|---|
longs: String / Number / BigInt |
type for 64-bit integers (Number may lose precision) |
enums: String |
enum names instead of numbers |
bytes: String |
bytes fields as base64 strings |
defaults: true |
include fields that have their default value |
arrays: true / objects: true |
include empty repeated and map fields |
oneofs: true |
add the virtual oneof property (payment above) |
A message's toJSON() (used by JSON.stringify) applies longs: String and enums: String, so the output is safe to send as JSON.
Validating input: verify and fromObject
encode() trusts its input. It doesn't check types, and a wrong type can silently disappear:
import protobuf from 'protobufjs';
const root = protobuf.loadSync('proto/shop.proto');
const Order = root.lookupType('shop.Order');
const b = Order.encode({ customer: 42 }).finish();
console.log('encoded', b, Order.decode(b));
encoded <Buffer 12 00> Message { items: [], metadata: {} }
The number 42 was written as an empty string. When the data comes from outside your code, either check it with verify() or convert it with fromObject():
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Order = root.lookupType('shop.Order');
console.log(Order.verify({ id: 1, customer: 42 }));
console.log(Order.verify({ status: 'STATUS_PAID' }));
const msg = Order.fromObject({
id: '9007199254740993',
customer: 42,
status: 'STATUS_SHIPPED',
items: [{ sku: 'A-100', quantity: '3', priceCents: 1990n }],
});
console.log(msg.customer, msg.status, msg.items[0].quantity);
console.log(msg.id.toString(), Number(msg.id.toString()));
const back = Order.toObject(Order.decode(Order.encode(msg).finish()), { longs: BigInt });
console.log(back.id, back.items[0].priceCents);
customer: string expected
status: enum value expected
42 3 3
9007199254740993 9007199254740992
9007199254740993n 1990n
verify()returnsnullwhen the object can be encoded as is, otherwise an error string. It's strict: an enum must be a number, not its name.fromObject()is lenient and converts: enum names to numbers, numeric strings to numbers, decimal strings andbiginttoLong, base64 strings to bytes9007199254740993(2^53 + 1) survives as aLongand as abigint, but not as a JavaScript number
Use fromObject() when accepting JSON from clients, and toObject() with the options you need when producing it.
Default values and field presence
In proto3, a field set to its default value (0, '', false, empty list, first enum value) is not written to the wire at all. The reader can't tell whether the field was set to the default or never set:
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Order = root.lookupType('shop.Order');
const a = Order.decode(Order.encode({ customer: '' }).finish());
const b = Order.decode(Order.encode({ note: '' }).finish());
console.log(JSON.stringify(a.customer), Object.hasOwn(a, 'customer'));
console.log(a.note, Object.hasOwn(a, 'note'));
console.log(JSON.stringify(b.note), Object.hasOwn(b, 'note'));
console.log(Order.encode({ note: '' }).finish().length);
"" false
null false
"" true
2
customer reads as '' from the prototype's default either way. note is declared optional, so an empty string is written (2 bytes: tag and zero length) and the decoded message has it as an own property. An unset optional field reads as null.
Use optional when "not set" means something different from the default, for example in a partial update where an empty string should clear a value but a missing field should leave it alone.
What the bytes look like
Knowing the wire format helps when debugging. Encode a small Item:
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Item = root.lookupType('shop.Item');
const bytes = Item.encode({ sku: 'A-100', quantity: 2, priceCents: 1990 }).finish();
console.log(Buffer.from(bytes).toString('hex').match(/../g).join(' '));
// default values are not written at all
console.log(Item.encode({ sku: '', quantity: 0, priceCents: 0 }).finish().length);
const r = protobuf.Reader.create(bytes);
while (r.pos < r.len) {
const tag = r.uint32();
const field = tag >>> 3, wireType = tag & 7;
if (wireType === 0) console.log(field, 'varint', r.uint64().toString());
else if (wireType === 2) console.log(field, 'len', JSON.stringify(r.string()));
else r.skipType(wireType);
}
0a 05 41 2d 31 30 30 10 02 18 c6 0f
0
1 len "A-100"
2 varint 2
3 varint 1990
A message is a sequence of fields, each starting with a tag (field_number << 3) | wire_type:
0ais field 1, wire type 2 (length-delimited), followed by length05and the 5 bytes ofA-10010is field 2, wire type 0 (varint), value0218is field 3, varintc6 0f. Varints store 7 bits per byte, low bits first, with the high bit meaning "more follows":0x46 + (0x0f << 7)= 70 + 1920 = 1990.
There are no field names and no type information, so you need the schema to make sense of the data. That's also why a reader can skip fields it doesn't know: the wire type tells it how many bytes to skip.
Schema evolution
Because fields are identified by number, you can change a schema without breaking existing readers or writers if you follow a few rules:
- adding a field is safe. Old readers skip it, new readers see the default when it's missing.
- removing a field is safe if you mark its number (and name)
reservedso nobody reuses it with a different meaning - renaming a field doesn't affect the binary format (it does affect the JSON form)
- changing a field's type is only safe between compatible types, such as
int32,uint32,int64,uint64andbool, orstringandbytesholding valid UTF-8 - never change a field's number
Here version 2 of a User removes email and adds emails and age. protobuf.parse() parses schema text directly, which is convenient for small examples:
import protobuf from 'protobufjs';
const v1 = protobuf.parse(`
syntax = "proto3";
message User {
string name = 1;
string email = 2;
}
`).root.lookupType('User');
const v2 = protobuf.parse(`
syntax = "proto3";
message User {
reserved 2;
reserved "email";
string name = 1;
repeated string emails = 3;
uint32 age = 4;
}
`).root.lookupType('User');
// new writer, old reader
const fromV2 = v2.encode({ name: 'alice', emails: ['a@example.com'], age: 30 }).finish();
console.log(v1.decode(fromV2));
// old writer, new reader
const fromV1 = v1.encode({ name: 'bob', email: 'bob@example.com' }).finish();
console.log(v2.decode(fromV1));
// keep unknown fields so a proxy can pass them on
const reader = protobuf.Reader.create(fromV2);
reader.discardUnknown = false;
const kept = v1.decode(reader);
console.log(kept.$unknowns?.length);
kept.name = 'ALICE';
console.log(v2.decode(v1.encode(kept).finish()));
Message { name: 'alice' }
Message { emails: [], name: 'bob' }
2
Message { emails: [ 'a@example.com' ], name: 'ALICE', age: 30 }
By default protobufjs drops unknown fields while decoding. Set discardUnknown = false on a reader (or protobuf.Reader.discardUnknown = false globally) to keep them in $unknowns. They are then written back by encode(), so a service running the old schema can modify a message without losing fields added by newer services.
Many messages in one file or stream
A protobuf message doesn't record its own length, so you can't simply concatenate messages. The standard solution is length-delimited encoding: each message is preceded by its size as a varint. encodeDelimited() and decodeDelimited() do this:
import { writeFile, readFile } from 'node:fs/promises';
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Item = root.lookupType('shop.Item');
const writer = protobuf.Writer.create();
for (let i = 1; i <= 3; i++) {
Item.encodeDelimited({ sku: `SKU-${i}`, quantity: i, priceCents: i * 100 }, writer);
}
await writeFile('items.bin', writer.finish());
const data = await readFile('items.bin');
console.log('file size:', data.length);
const reader = protobuf.Reader.create(data);
while (reader.pos < reader.len) {
const item = Item.decodeDelimited(reader);
console.log(Item.toObject(item, { longs: Number }));
}
file size: 38
{ sku: 'SKU-1', quantity: 1, priceCents: 100 }
{ sku: 'SKU-2', quantity: 2, priceCents: 200 }
{ sku: 'SKU-3', quantity: 3, priceCents: 300 }
The same framing works for messages sent over a TCP socket. Java's writeDelimitedTo() / parseDelimitedFrom() and the equivalent functions in other languages use the same format, so the file can be read from other languages.
Protobuf over HTTP
Protobuf is just bytes, so it can be sent in any HTTP body. The convention is the application/x-protobuf (or application/protobuf) content type. A server that accepts an order and returns it with a new status, and a fetch client for it:
import http from 'node:http';
import { buffer } from 'node:stream/consumers';
import protobuf from 'protobufjs';
const root = await protobuf.load('proto/shop.proto');
const Order = root.lookupType('shop.Order');
const Status = root.lookupEnum('shop.Status');
const server = http.createServer(async (req, res) => {
if (req.method !== 'POST' || req.headers['content-type'] !== 'application/x-protobuf') {
res.writeHead(415).end();
return;
}
const body = await buffer(req);
let order;
try {
order = Order.decode(body);
} catch (err) {
res.writeHead(400).end(err.message);
return;
}
console.log('server got order for', order.customer, 'with', order.items.length, 'items');
order.status = Status.values.STATUS_PENDING;
res.writeHead(200, { 'content-type': 'application/x-protobuf' });
res.end(Order.encode(order).finish());
});
server.listen(0, '127.0.0.1', async () => {
const { port } = server.address();
const res = await fetch(`http://127.0.0.1:${port}/orders`, {
method: 'POST',
headers: { 'content-type': 'application/x-protobuf' },
body: Order.encode({ customer: 'alice', items: [{ sku: 'A-100', quantity: 1 }] }).finish(),
});
const reply = Order.decode(new Uint8Array(await res.arrayBuffer()));
console.log(res.status, Status.valuesById[reply.status]);
const bad = await fetch(`http://127.0.0.1:${port}/orders`, {
method: 'POST',
headers: { 'content-type': 'application/x-protobuf' },
body: new Uint8Array([0x12, 0x10, 0x61]), // says 16 bytes follow, has 1
});
console.log(bad.status, await bad.text());
server.close();
});
server got order for alice with 1 items
200 STATUS_PENDING
400 index out of range: 2 + 16 > 3
decode() throws on truncated or malformed data, so always wrap it in try/catch when the bytes come from the network. Also limit the request body size: a small message can declare large lengths and nested structures, and decoding untrusted input costs memory. See HTTP client and server for more about the http module.
For RPC between services, gRPC (@grpc/grpc-js with @grpc/proto-loader) and Connect (@connectrpc/connect, built on Protobuf-ES) use protobuf messages with service definitions from the same .proto files.
Generating static code with pbjs
Loading .proto files at runtime is convenient, but you get no type checking and the parser is part of your bundle. The pbjs tool from protobufjs-cli (npm install --save-dev protobufjs-cli) generates JavaScript code and TypeScript declarations ahead of time:
npx pbjs -t static-module -w esm -o gen/shop.js --dts proto/shop.proto
This writes gen/shop.js, which imports only protobufjs/minimal.js (no parser, no reflection), and gen/shop.d.ts. Using it from TypeScript (run here directly with node static.ts, which strips types):
import { shop } from './gen/shop.js';
const order = shop.Order.create({
id: 7,
customer: 'carol',
status: shop.Status.STATUS_PAID,
items: [{ sku: 'C-300', quantity: 4, priceCents: 250 }],
payment: 'iban',
iban: 'DE89370400440532013000',
});
const bytes = shop.Order.encode(order).finish();
const decoded = shop.Order.decode(bytes);
if (decoded.payment === 'iban') {
console.log('pays with IBAN', decoded.iban);
}
console.log(shop.Order.toObject(decoded, { longs: Number, enums: String }));
pays with IBAN DE89370400440532013000
{
id: 7,
customer: 'carol',
status: 'STATUS_PAID',
items: [ { sku: 'C-300', quantity: 4, priceCents: 250 } ],
iban: 'DE89370400440532013000'
}
The declarations catch type errors such as shop.Order.create({ customer: 42 }):
error TS2769: No overload matches this call.
The last overload gave the following error.
Type 'number' is not assignable to type 'string'.
Use -t json-module instead of static-module for a smaller module that keeps reflection metadata (so toObject, verify and friends still work generically) but skips .proto parsing at runtime.
Protobuf-ES (@bufbuild/protobuf)
Protobuf-ES is a newer implementation that always uses generated code. Messages are plain objects, 64-bit integers are bigint, oneofs are discriminated unions, and the JSON mapping follows the official ProtoJSON spec. It passes the protobuf conformance tests and is used by the Connect RPC framework.
Install the runtime, the code generator plugin and the buf CLI:
npm install @bufbuild/protobuf
npm install --save-dev @bufbuild/protoc-gen-es @bufbuild/buf
Configure generation in buf.gen.yaml:
version: v2
inputs:
- directory: proto
plugins:
- local: protoc-gen-es
out: src/gen
opt: target=js+dts
npx buf generate creates src/gen/shop_pb.js and src/gen/shop_pb.d.ts. Use target=ts to get a single .ts file instead; note that it contains TypeScript enum declarations, which Node.js type stripping doesn't support, so it needs to be compiled by tsc or a bundler.
Each message gets a ...Schema descriptor that you pass to the runtime functions:
import { create, toBinary, fromBinary, toJson, fromJson, equals } from '@bufbuild/protobuf';
import { OrderSchema, Status } from './src/gen/shop_pb.js';
const order = create(OrderSchema, {
id: 1001n,
customer: 'alice',
status: Status.PAID,
items: [{ sku: 'A-100', quantity: 2, priceCents: 1990n }],
metadata: { source: 'web' },
payment: { case: 'cardLast4', value: '4242' },
});
const bytes = toBinary(OrderSchema, order);
console.log(bytes.length, 'bytes');
const decoded = fromBinary(OrderSchema, bytes);
console.log(decoded.id, decoded.items[0].priceCents);
switch (decoded.payment.case) {
case 'cardLast4':
console.log('card ending in', decoded.payment.value);
break;
case 'iban':
console.log('bank transfer', decoded.payment.value);
break;
}
const json = toJson(OrderSchema, decoded);
console.log(JSON.stringify(json));
const again = fromJson(OrderSchema, json);
console.log(equals(OrderSchema, decoded, again));
47 bytes
1001n 1990n
card ending in 4242
{"id":"1001","customer":"alice","status":"STATUS_PAID","items":[{"sku":"A-100","quantity":2,"priceCents":"1990"}],"metadata":{"source":"web"},"cardLast4":"4242"}
true
Differences from protobufjs:
create()fills in defaults and returns a typed plain object; there are no classes orLong- the generator strips the enum's common prefix:
STATUS_PAIDbecomesStatus.PAID - a oneof is a single property
{ case, value }, so TypeScript knowsvalue's type after checkingcase, and two members can never be set at once toJson()/fromJson()implement ProtoJSON: 64-bit integers as strings, enums by name, well-known types in their special forms
Both libraries produce standard protobuf bytes, so they can read each other's output, as well as data from Go, Java, Python or any other implementation.
Well-known types
Protobuf comes with a set of common message types in the google.protobuf package, such as Timestamp, Duration, Struct, Any and wrappers like StringValue. A schema in proto/audit.proto that uses two of them:
syntax = "proto3";
package shop;
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
message AuditEvent {
string action = 1;
google.protobuf.Timestamp at = 2;
google.protobuf.Duration took = 3;
}
buf finds the imported files on its own. Protobuf-ES ships them precompiled in @bufbuild/protobuf/wkt, along with helpers to convert to and from JavaScript values:
import { create, toBinary, fromBinary, toJsonString } from '@bufbuild/protobuf';
import { timestampFromDate, timestampDate, durationFromMs, durationMs } from '@bufbuild/protobuf/wkt';
import { AuditEventSchema } from './src/gen/audit_pb.js';
const event = create(AuditEventSchema, {
action: 'order.paid',
at: timestampFromDate(new Date('2026-10-17T12:30:00.250Z')),
took: durationFromMs(1500),
});
console.log(event.at);
console.log(toJsonString(AuditEventSchema, event));
const back = fromBinary(AuditEventSchema, toBinary(AuditEventSchema, event));
console.log(timestampDate(back.at!).toISOString(), durationMs(back.took!));
{
'$typeName': 'google.protobuf.Timestamp',
seconds: 1792240200n,
nanos: 250000000
}
{"action":"order.paid","at":"2026-10-17T12:30:00.250Z","took":"1.500s"}
2026-10-17T12:30:00.250Z 1500
A Timestamp is stored as seconds and nanoseconds since the Unix epoch, but in ProtoJSON it becomes an RFC 3339 string. Message fields are optional by nature, which is why back.at has type Timestamp | undefined.
Tips
- keep
.protofiles in one place shared by all services (a separate repository or a directory in a monorepo) and generate code from them in each project - add a
"generate"script topackage.json("buf generate"or thepbjscommand) and decide whether generated code is committed or built in CI buf lintchecks naming and style rules andbuf breaking --against <old version>detects incompatible schema changes before they ship- start enums with an
..._UNSPECIFIED = 0value and prefix values with the enum name, as done forStatus - protobuf is not self-describing: storing the bytes without knowing which message type and schema version they are makes them hard to read later
- for data that people need to read or edit, or for browser APIs where size doesn't matter, plain JSON is often simpler
Summary
| Task | protobufjs | Protobuf-ES |
|---|---|---|
| load schema | await protobuf.load('x.proto') |
npx buf generate, then import XSchema |
| get a type | root.lookupType('pkg.Msg') |
import { MsgSchema } from './gen/x_pb.js' |
| create a message | Msg.create({...}) / Msg.fromObject({...}) |
create(MsgSchema, {...}) |
| encode | Msg.encode(obj).finish() |
toBinary(MsgSchema, msg) |
| decode | Msg.decode(bytes) |
fromBinary(MsgSchema, bytes) |
| check input | Msg.verify(obj) returns null or an error |
TypeScript types |
| to plain object / JSON | Msg.toObject(msg, { longs: String, enums: String }) |
toJson(MsgSchema, msg) |
| 64-bit integers | Long, or longs: BigInt in toObject |
bigint |
| oneof | msg.payment names the set field |
msg.payment.case and msg.payment.value |
| length-delimited | encodeDelimited() / decodeDelimited() |
sizeDelimitedEncode() / sizeDelimitedDecodeStream() from @bufbuild/protobuf/wire |
| generate code | npx pbjs -t static-module -w esm -o x.js --dts x.proto |
npx buf generate |