How to Implement gRPC-Web from the Browser
Bridge browsers to a gRPC backend with gRPC-Web: set up the proxy, choose the wire mode, handle trailers, and expose deadlines.
On this page
Introduction
gRPC is an efficient remote procedure call protocol built on HTTP/2, with typed messages, streaming, and rich status codes. The catch is that a browser cannot speak it directly: JavaScript has no way to control HTTP/2 frames or read trailers, both of which gRPC depends on. gRPC-Web is the bridge. It re-encodes the protocol into something a browser can send over ordinary HTTP, and a proxy translates between the two so the backend remains a normal gRPC server.
This tutorial wires a browser client to a gRPC backend through a gRPC-Web proxy. It covers the role of the proxy, the wire modes available, how trailers carry the final status, how to map gRPC status codes to application errors, and why deadlines and cancellation matter. The examples reference a generated TypeScript client, but the architecture is language-agnostic.
Understand the proxy’s role
The browser sends an HTTP request that a proxy recognizes as gRPC-Web. The proxy converts it into a native gRPC call over HTTP/2 to the backend, waits for the response and trailers, and re-encodes the result into a form the browser can parse. Envoy provides a gRPC-Web filter, and several application servers expose the translation natively. The backend stays a plain gRPC service and does not need to know a browser is involved.
This indirection has consequences. The proxy becomes part of your request path, so its timeout, buffer limits, and CORS configuration all apply. A streaming response passes through the proxy, which must be configured to flush rather than buffer, or the client sees the whole stream arrive at once at the end instead of progressively. CORS must allow the gRPC-Web content types and any custom headers the client sends.
Choose the wire mode
gRPC-Web supports two modes. Unary mode sends a single request and receives a single response, which covers the majority of RPCs. Server-streaming mode sends one request and receives a sequence of messages, which suits subscriptions and large result sets delivered incrementally. Client streaming and full-duplex streaming are not available, because a browser cannot half-close a request body the way the protocol needs. If you need bidirectional streaming, use a WebSocket transport instead of gRPC-Web.
The mode is encoded in the content type and in how the body is framed. A text mode sends base64-encoded frames, which is readable in devtools but larger; a binary mode sends raw bytes, which is smaller but opaque. Prefer binary in production for size, and switch to text temporarily if you must debug a payload by eye.
import { createPromiseClient } from '@connectrpc/connect';
import { createConnectTransport } from '@connectrpc/connect-web';
const transport = createConnectTransport({
baseUrl: 'https://api.example.com',
useBinaryFormat: true, // smaller on the wire
});
const client = createPromiseClient(ReportService, transport);
const report = await client.getReport({ id: 'r-1' });
Handle trailers and the final status
In native gRPC the final status and any trailing metadata travel in HTTP/2 trailers. Browsers cannot read trailers, so gRPC-Web encodes them either as a base64 trailer frame at the end of the body or, in some proxies, as regular response headers with a grpc-status prefix. This is why a gRPC-Web client must read the status from the trailer frame, not just from the HTTP status code. A successful HTTP 200 does not mean the RPC succeeded.
Map the gRPC status codes to application behavior explicitly. Codes such as DEADLINE_EXCEEDED, UNAVAILABLE, and RESOURCE_EXHAUSTED are candidates for retry or backoff. INVALID_ARGUMENT and PERMISSION_DENIED are terminal and should surface to the user. UNIMPLEMENTED points at a version mismatch between the client’s generated stubs and the server. Centralize the mapping in one error translation layer so each call site does not invent its own rules.
import { Code, ConnectError } from '@connectrpc/connect';
function translate(err: unknown): { message: string; retryable: boolean } {
if (err instanceof ConnectError) {
switch (err.code) {
case Code.Unavailable:
case Code.DeadlineExceeded:
case Code.ResourceExhausted:
return { message: 'Service busy, please retry.', retryable: true };
case Code.InvalidArgument:
return { message: 'Invalid request.', retryable: false };
case Code.PermissionDenied:
return { message: 'Not allowed.', retryable: false };
default:
return { message: 'Unexpected error.', retryable: false };
}
}
return { message: 'Network error.', retryable: true };
}
Set deadlines and cancel calls
Every gRPC call should carry a deadline. Without one, a hung backend leaves the browser waiting until the transport gives up, and the user has no feedback. A deadline is an absolute time budget for the call; the server can check it and stop work early, and the client sees DEADLINE_EXCEEDED. Set the deadline from the interaction, for example a short budget for a lookup and a longer one for a report, and never leave it unbounded.
Cancel calls when the user navigates away or the component unmounts. A streaming subscription that keeps running after the page is gone wastes server resources and can update state that no longer exists, causing errors. Tie the call’s signal to the component lifecycle and abort it on teardown. Cancellation is not just a client concern: the server should observe the cancellation and stop producing.
async function loadReport(client: unknown, signal: AbortSignal) {
const timeout = AbortSignal.timeout(5000); // 5s deadline
const combined = AbortSignal.any([signal, timeout]);
// client.getReport({ id: 'r-1' }, { signal: combined })
return combined;
}
Test success and deadline paths
Test a successful unary call and assert the parsed response. Test a server-streaming call and assert the messages arrive in order and the stream closes cleanly. Then test failure paths: a non-existent id should yield NOT_FOUND, a slow handler should yield DEADLINE_EXCEEDED after the budget, and an aborted call should stop without a console error. These tests catch the common bug of ignoring the trailer status and treating a failed RPC as a success.
curl -s -X POST http://localhost:8080/pkg.Service/GetReport \
-H 'content-type: application/grpc-web+proto' \
--data-binary @request.bin -o response.bin -D -
# expect a grpc-status trailer frame at the end of the body
Common pitfalls
Forgetting the proxy entirely so the browser cannot reach a plain gRPC server, buffering a stream at the proxy and losing progressive delivery, reading only the HTTP status and missing the gRPC trailer status, leaving calls without deadlines, and not cancelling on unmount are the recurring mistakes. Each has a concrete fix in the proxy configuration or the client wrapper, and the deadline and failure tests expose them early.
Conclusion
gRPC-Web lets a typed gRPC backend serve browsers through a translating proxy. Configure the proxy for CORS and streaming, choose unary or server-streaming according to the endpoint, read the final status from trailers rather than the HTTP code, map gRPC codes to application behavior, and give every call a deadline and a cancellation path. Self-check by asserting that a slow handler yields DEADLINE_EXCEEDED and that an aborted stream stops cleanly. With the bridge in place, the browser gets gRPC’s ergonomics without gRPC’s framing.
Sources: gRPC-Web documentation, Envoy: gRPC-Web filter, gRPC: Status codes.
FAQ
- Why can't browsers speak gRPC directly?
- Browser APIs do not expose the HTTP/2 framing and trailer control that gRPC requires. gRPC-Web re-encodes the protocol over regular HTTP so a proxy can translate; the browser never sends true HTTP/2 gRPC frames.
- Does gRPC-Web support client streaming?
- No. Browsers cannot half-close a request stream the way client streaming needs. Emulate a client stream by sending a sequence of unary requests or by using a bidirectional transport such as WebSocket alongside gRPC-Web.
Report a problem with this articleOpens a pre-filled issue on GitHub.