Migrating from v1
Version 2 adds reflection, Editions support, new presence behavior, and a new generated API based on schemas instead of classes.
To migrate, update dependencies, regenerate code, and then adjust call sites in your application.
Update packages
Section titled “Update packages”Install the v2 packages you use:
npm install @bufbuild/protobuf@^2.0.0 @bufbuild/protoc-gen-es@^2.0.0The main packages are:
Then regenerate all code with the updated plugin.
Review option defaults
Section titled “Review option defaults”Some plugin defaults changed in v2:
import_extensionnow defaults tonone. If your config still saysimport_extension=none, you can remove it.ts_nocheckis now off by default. If you still need// @ts-nocheck, setts_nocheck=trueexplicitly.
Remote plugin users
Section titled “Remote plugin users”If you use the remote plugin instead of a locally installed binary, update the version in buf.gen.yaml:
version: v2plugins: - remote: buf.build/bufbuild/es:v2.12.0 out: genIf you use generated SDKs from the BSR, update those packages to versions built with the v2 plugin.
Update your code
Section titled “Update your code”The biggest change is that generated messages are no longer classes.
Create messages with create() and a schema instead of new:
import { User } from "./gen/example_pb"; import { create } from "@bufbuild/protobuf"; import { UserSchema } from "./gen/example_pb";
let user = new User({ let user = create(UserSchema, { firstName: "Homer",});Serialization helpers are now standalone functions that take both schema and message:
import type { User } from "./gen/example_pb"; import { UserSchema } from "./gen/example_pb"; import { toJsonString } from "@bufbuild/protobuf";
function show(user: User) { alert(user.toJsonString()); alert(toJsonString(UserSchema, user));}Messages no longer implement toJSON. Convert them with toJson() before passing them to JSON.stringify().
Quick reference
Section titled “Quick reference”| v1 | v2 |
|---|---|
new User({ firstName: "Homer" }) | create(UserSchema, { firstName: "Homer" }) |
msg.toBinary() | toBinary(UserSchema, msg) |
User.fromBinary(bytes) | fromBinary(UserSchema, bytes) |
msg.toJsonString() | toJsonString(UserSchema, msg) |
User.fromJsonString(str) | fromJsonString(UserSchema, str) |
msg.toJson() | toJson(UserSchema, msg) |
msg.clone() | clone(UserSchema, msg) |
msg.equals(other) | equals(UserSchema, msg, other) |
Other notable changes
Section titled “Other notable changes”google.protobuf.Structfields are now generated asJsonObject.- Proto2 fields support default values and are no longer generated as optional in the same way as v1.
toPlainMessage()andPlainMessage<T>are no longer needed. For proto3,create(UserSchema)already returns a plain object. ReplacePlainMessage<User>withUser.- Well-known types moved to the
@bufbuild/protobuf/wktsubpath export.
For large applications, you can migrate incrementally. If necessary, run both versions side by side while you update call sites.