3

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');

Fireburn
  • 981
  • 6
  • 20

2 Answers2

1

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

  • Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. – jasie Sep 14 '21 at 07:10
1

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.
Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167