Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

grpc-web

> 编程语言
Open source

gRPC for Web Clients

9.2K stars0 likes1 views
WebsiteGitHub

About

gRPC for Web Clients

gRPC Web ·

A JavaScript implementation of [gRPC][] for browser clients. For more information, including a quick start, see the [gRPC-web documentation][grpc-web-docs].

gRPC-web clients connect to gRPC services via a special proxy; by default, gRPC-web uses [Envoy][].

In the future, we expect gRPC-web to be supported in language-specific web frameworks for languages such as Python, Java, and Node. For details, see the roadmap.

Streaming Support

gRPC-web currently supports 2 RPC modes:

  • Unary RPCs (example)
  • Server-side Streaming RPCs (example) (NOTE: Only when grpcwebtext mode is used.)

Client-side and Bi-directional streaming is not currently supported (see streaming roadmap).

Quick Start

Eager to get started? Try the [Hello World example][]. From this example, you'll learn how to do the following:

  • Define your service using protocol buffers
  • Implement a simple gRPC Service using Node.js
  • Configure the Envoy proxy
  • Generate protobuf message classes and client service stub for the client
  • Compile all the JS dependencies into a static library that can be consumed by the browser easily

Advanced Demo: Browser Echo App

You can also try to run a more advanced Echo app from the browser with a streaming example.

From the repo root directory:

bash
$ docker-compose pull prereqs node-server envoy commonjs-client
$ docker-compose up node-server envoy commonjs-client

Open a browser tab, and visit http://localhost:8081/echotest.html.

To shutdown: docker-compose down.

Runtime Library

The gRPC-web runtime library is available on npm:

bash
$ npm i grpc-web

Code Generator Plugins

(Prerequisite) 1. Protobuf (protoc)

If you don't already have protoc installed, download it first from here and install it on your PATH.

If you use Homebrew (on macOS), you could run:

bash
brew install protobuf

(Prerequisite) 2. Protobuf-javascript (protoc-gen-js)

If you don't have protoc-gen-js installed, download it from protocolbuffers/protobuf-javascript and install it on your PATH.

Or, use the third-party npm installer:

bash
npm install -g protoc-gen-js

3. Install gRPC-Web Code Generator

You can download the protoc-gen-grpc-web protoc plugin from our release page:

Make sure all executables are discoverable from your PATH.

For example, on macOS, you can do:

bash
sudo mv protoc-gen-grpc-web-2.0.2-darwin-aarch64 \
    /usr/local/bin/protoc-gen-grpc-web

chmod +x /usr/local/bin/protoc-gen-grpc-web

Note: If you are using our Docker setup, the prereqs image already includes both protoc and the protoc-gen-grpc-web plugin on the PATH.

(Optional) 4. Verify Installations

You can optionally verify the plugins work by following our Hello World example:

bash
cd net/grpc/gateway/examples/helloworld

protoc -I=. helloworld.proto \
  --js_out=import_style=commonjs:. \
  --grpc-web_out=import_style=commonjs,mode=grpcwebtext:.

After the command runs successfully, you should now see two new files generated in the current directory. By running:

ls -1 *_pb.js

Installation is successful if you see the following 2 files:

  • helloworld_pb.js — Generated by protoc-gen-js plugin
  • helloworld_grpc_web_pb.js - Generated by gRPC-Web plugin

Client Configuration Options

Typically, you will run the following command to generate the proto messages and the service client stub from your .proto definitions:

bash
protoc -I=$DIR echo.proto \
  --js_out=import_style=commonjs:$OUT_DIR \
  --grpc-web_out=import_style=commonjs,mode=grpcwebtext:$OUT_DIR

You can then use Browserify, Webpack, Closure Compiler, etc. to resolve imports at compile time.

Import Style

import_style=closure: The default generated code has Closure goog.require() import style.

import_style=commonjs: The CommonJS style require() is also supported.

import_style=commonjs+dts: In addition to above, a .d.ts typings file will also be generated for the protobuf messages and service stub

import_style=typescript: The service stub will be generated in TypeScript. See TypeScript Support below for information on how to generate TypeScript files.

Note: The commonjs+dts and typescript styles are only supported by --grpc-web_out=import_style=..., not by --js_out=import_style=....

Wire Format Mode

For more information about the gRPC-web wire format, see the specification.

mode=grpcwebtext: The default generated code sends the payloads in the grpc-web-text format.

  • Content-Type: application/grpc-web-text
  • Payloads are base64-encoded.
  • Both unary and server streaming calls are supported.

mode=grpcweb: A binary protobuf format is also supported.

  • Content-Type: application/grpc-web+proto
  • Payloads are in the binary protobuf format.
  • Only unary calls are supported.

How It Works

Let's take a look at how gRPC-web works with a simple example. You can find out how to build, run and explore the example yourself in Build and Run the Echo Example.

1. Define your service

The first step when creating any gRPC service is to define it. Like all gRPC services, gRPC-web uses protocol buffers to define its RPC service methods and their message request and response types.

protobuf
message EchoRequest {
  string message = 1;
}

...

service EchoService {
  rpc Echo(EchoRequest) returns (EchoResponse);

  rpc ServerStreamingEcho(ServerStreamingEchoRequest)
      returns (stream ServerStreamingEchoResponse);
}

2. Run the server and proxy

Next you need to have a gRPC server that implements the service interface and a gateway proxy that allows the client to connect to the server. Our example builds a simple Node gRPC backend server and the Envoy proxy.

For the Echo service: see the service implementation.

For the Envoy proxy: see the config YAML file.

3. Write your JS client

Once the server and gateway are up and running, you can start making gRPC calls from the browser!

Create your client:

javascript
var echoService = new proto.mypackage.EchoServiceClient(
  'http://localhost:8080');

Make a unary RPC call:

javascript
var request = new proto.mypackage.EchoRequest();
request.setMessage(msg);
var metadata = {'custom-header-1': 'value1'};
echoService.echo(request, metadata, function(err, response) {
  if (err) {
    console.log(err.code);
    console.log(err.message);
  } else {
    console.log(response.getMessage());
  }
});

Server-side streaming:

javascript
var stream = echoService.serverStreamingEcho(streamRequest, metadata);
stream.on('data', function(response) {
  console.log(response.getMessage());
});
stream.on('status', function(status) {
  console.log(status.code);
  console.log(status.details);
  console.log(status.metadata);
});
stream.on('end', function(end) {
  // stream end signal
});

// to close the stream
stream.cancel();

For an in-depth tutorial, see this page.

Setting a Deadline

You can set a deadline for your RPC by setting a deadline header. The value should be a Unix timestamp, in milliseconds.

javascript
var deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 1);

client.sayHelloAfterDelay(request, {deadline: deadline.getTime().toString()},
  (err, response) => {
    // err will be populated if the RPC exceeds the deadline
    ...
  });

TypeScript Support

The grpc-web runtime library is now fully written in TypeScript! This provides first-class type safety, zero runtime dependencies, and built-in type definitions out of the box.

You can simply import it into your TypeScript projects without needing external typings.

When using the protoc-gen-grpc-web protoc plugin, mentioned above, pass in either:

  • import_style=commonjs+dts: existing CommonJS style stub + .d.ts typings
  • import_style=typescript: full TypeScript output

Do not use import_style=typescript for --js_out, it will silently be ignored. Instead you should use --js_out=import_style=commonjs, or --js_out=import_style=commonjs,binary if you are using mode=grpcweb. The --js_out plugin will generate JavaScript code (echo_pb.js), and the -grpc-web_out plugin will generate a TypeScript definition file for it (echo_pb.d.ts). This is a temporary hack until the --js_out supports TypeScript itself.

For example, this is the command you should use to generate TypeScript code using the binary wire format:

bash
protoc -I=$DIR echo.proto \
  --js_out=import_style=commonjs,binary:$OUT_DIR \
  --grpc-web_out=import_style=typescript,mode=grpcweb:$OUT_DIR

It will generate the following files:

  • EchoServiceClientPb.ts - Generated by --grpc-web_out, contains the TypeScript gRPC-web code.
  • echo_pb.js - Generated by --js_out, contains the JavaScript Protobuf code.
  • echo_pb.d.ts - Generated by --grpc-web_out, contains TypeScript definitions for echo_pb.js.

Using Callbacks

typescript
import * as grpcWeb from 'grpc-web';
import {EchoServiceClient} from './EchoServiceClientPb';
import {EchoRequest, EchoResponse} from './echo_pb';

const echoService = new EchoServiceClient('http://localhost:8080', null, null);

const request = new EchoRequest();
request.setMessage('Hello World!');

const call = echoService.echo(request, {'custom-header-1': 'value1'},
  (err: grpcWeb.RpcError, response: EchoResponse) => {
    console.log(response.getMessage());
  });
call.on('status', (status: grpcWeb.Status) => {
  // ...
});

(See here for the full list of possible .on(...) callbacks.)

(Optional) Using Promises (Limited Features)

NOTE: It is not possible to access the .on(...) callbacks (e.g. for metadata and status) when Promise is used.

typescript
// Create a Promise client instead
const echoService = new EchoServicePromiseClient('http://localhost:8080', null, null);

... (same as above)

this.echoService.echo(request, {'custom-header-1': 'value1'})
  .then((response: EchoResponse) => {
    console.log(`Received response: ${response.getMessage()}`);
  }).catch((err: grpcWeb.RpcError) => {
    console.log(`Received error: ${err.code}, ${err.message}`);
  });

For the full TypeScript example, see ts-example/client.ts and the instructions to run.

Custom Interceptors

Custom interceptors can be implemented and chained, which could be useful for features like auth, retries, etc.

There are 2 types of interceptors (interfaces):

  • UnaryInterceptor (doc, example) - Intercept Unary

Issues· 171 open

View all issuesOpen on GitHub
  • #1554

    prereqs Dockerfile fails to build: bullseye release file is expired

    Updated Sep 9, 2026
  • #1543

    When grpc-web (browser) receives a 400 or 500 level error, metadata is empty

    Updated Aug 5, 2026
  • #522

    Is there any way to circumvent the browsers limitations for concurrent connections http2

    Updated Jul 20, 2026
  • #1014

    how to get grpc-web custom-error

    Updated Jun 19, 2026
  • #702

    Path prefixes: how?

    Updated Jun 19, 2026
  • #1011

    How to send metadata using an web Interceptor?

    Updated Jun 19, 2026
  • #957

    `grpc-status` and `grpc-message` are missing in response headers

    Updated Jun 19, 2026
  • #955

    normalise import path in generated code

    Updated Jun 19, 2026
  • #943

    TS alternative to option go_package = "dir/dir/stubs/v1"

    Updated Jun 19, 2026
  • #937

    More examples with interceptors

    Updated Jun 19, 2026

> Tags

JavaScriptgrpcjavascriptweb

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言