Fireburn
Fireburn

Reputation: 1021

Using GRPC-Web without NodeJS

How do you use GRPC-Web on the browser? I mean, in pure browser code, without any NodeJS involved.

Official example from here: https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld are mainly NodeJS oriented.

Is there way to use GRPC-Web in pure Javascript form without:

const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');

Meaning, just standard <script>-way of adding Javascript dependencies? And be able to do: var client = new GreeterClient('http://localhost:8080');

Upvotes: 4

Views: 1834

Answers (2)

Ben Butterworth
Ben Butterworth

Reputation: 28948

Use grpc-web, not @grpc/grpc-js npm package.

The example provided in Write Client Code uses @grpc/grpc-js, which only works on NodeJS.

To use your protobufs and gRPC services defined in your .proto files, you need to generate your code using grpc-web. Then, import those generated files and use them.


Some things I learnt along the way:

  • You can't really use protobufjs with gprc-web in browsers, you need to use grpc-web and google-protobuf. If someone has an alternative solution, let me know please.
  • The generated code in grpc-web is not very nice - it is difficult to read and doesn't have all the features of protobufs. You need to have a lot of Javascript and bundling experience to use it.
  • grpc-web is more limited than gRPC. NodeJS runs gRPC, but in the browser, you have to use grpc-web, and must run a gRPC proxy to translate gRPC-web into/from gRPC.

Upvotes: 1

Viacheslav Bilohlazov
Viacheslav Bilohlazov

Reputation: 31

Yes. You need to bundle your sources with webpack. This step is also described in the documentation you mentioned. At the bottom of the readme:

Just config your webpack to expose variable:

client.js

...
export function instantiateGreeterClient(...) { 
    return new GreeterClient(...)
};

webpack.config.js

module.exports = {
   ...
   entry: './path/to/client.js',
   output: {
      path: './bundle/js/',
      filename: 'grpc.js',
      library: {
          name: 'grpc',
          type: 'umd',
      },
   ...
}

And after that import your bundle as usual. Now you be able to use all defined variables in your script tag code as

<script src="path/to/grpc.js"></script>
<script> 
    const client = grpc.instantiateGreeterClient(...)
    ...
</script>

More information can be found in webpack documentation

Upvotes: 1

Related Questions