Protobuf in Reactjs
Protocol Buffer is the mechanism for serializing structured data. The characters such as { }, [ ], “, , are used in JSON objects which are not data, even though we are trying to send and receive those characters. Protobuf are unreadable and does not use such characters. Hence, minimize the payload which we are trying to send or receive of around 40–50% or even more.
Let’s start Protobuf by createing .proto file.
let’s take a basic and simple example. We want to define user Register message format where each request has a string of firstName, lastName, email and suspended as boolean.
Here the first line syntax = “proto3” specifies that we are using proto3 syntax and named the file as user.proto
Compile the .proto file
In order to compile .proto file we need to install protoc compiler and go to the directory where .proto file is located and run the command
After running the command, it will generate user_pb.js file of user.proto file.
Import the generated file and use the Protobuf Object
We need to install google-protobuf in the project.
Now, we can set data
And now we can serialize data as
const serializedData = registerData.serializeBinary();
And can deserialized and convert back to object as
const desData = userData.User.deserializeBinary(serializedData).toObject();
Conclusion
In this way, we can serialize and deserialize the JSON objects.