Using Protobuf in React-Native

Andresh Singh
2 min readDec 16, 2018

--

You might be involved in a project using Protocol Buffers instead of JSON sooner or later. The library that we will be using to use Protobuf in our React-Native application is google-protobuf.

What is Protobuf?

Protocol Buffers are basically a way to serialize structured data. JSON object has a lot of characters like{ } [ ] , : " which are not the data which we are trying to send or receive. Protobuf doesn’t use such kinds of characters and the serialized object reduces the payload as much by roughly 40% or more. Needless to tell, the serialized object is also unreadable, unlike JSON objects.

Step 1: Creating a Proto file

Lets Start by creating a .proto file.

We want the information we’re serializing to be structured by defining protocol buffer message types in .proto files. Each protocol buffer message is a small logical record of information, containing a series of name-value pairs.

So, lets create a basic message User which stores the email and password of any user.

syntax = "proto3";message User {
string email = 1;
string password = 2;
}

Here, the syntax = "proto3"; sentence tells the compiler that we’re using the version 3 of protocol buffers.

We have initialized a User object which has two field ,i.e. Email and Password. I have named the file auth.proto .

Step 2: Compilation

We then compile the .protofile using the protoc compiler.

Note: You need to install the protoc compiler first.

We simply go the directory where the .proto file is located and run …

protoc --proto_path=./ --js_out=import_style=commonjs,binary:./ *.proto

This command then generates the auth_pb.js file of the auth.proto file.

Step 3: Importing the file

We simple paste the .js file generated from the .proto file and require it.

const auth = require(‘./auth_pb’);

Note: You will need to install google-protobuf in your project.

Step 4: Using Protobuf Object

We have to first create an instance of the User message. The syntax is …

const authObj = new auth.User();

We can now set the email and password as …

authObj.setEmail("singhandresh09@gmail.com");authObj.setPassword("Password@1234");

Serializing the object is as easy as …

const serializedData = authObj.serializeBinary();

We can then deserialize the data as ..

const desData = auth.User.deserializeBinary(serializedData);

To convert the deserialized data to JSON, we simply do…

const jsonData = desData.toObject();

Conclusion

Hence in this way we can easily use Protobuf in our applications.

--

--