🌐 Web Development

gRPC-Web

A protocol for using gRPC in browsers

Detailed Explanation

gRPC-Web is a protocol that allows web browsers to call gRPC services. It was developed because regular gRPC cannot be used directly due to the browser's HTTP/2 limitations.

When a gRPC-Web client in the browser sends a request, a proxy (such as Envoy) converts it to standard gRPC and communicates with the backend service. This allows the frontend to also take advantage of gRPC's benefits.

However, bidirectional streaming is not supported, and a proxy server is required.

Code Example

Generate a client from a proto file

# After installing protobuf and the grpc-web plugin protoc -I=. user.proto \ --js_out=import_style=commonjs:./generated \ --grpc-web_out=import_style=typescript,mode=grpcwebtext:./generated

Using the TypeScript client

import { UserServiceClient } from './generated/UserServiceClientPb'; import { GetUserRequest, User } from './generated/user_pb'; // 클라이언트 생성 (Envoy 프록시 주소) const client = new UserServiceClient('http://localhost:8080'); // Unary 호출 const request = new GetUserRequest(); request.setId(1); client.getUser(request, {}, (err, response: User) => { if (err) { console.error(err); return; } console.log(response.getName()); // "홍길동" console.log(response.getEmail()); }); // Promise 래퍼 사용 async function fetchUser(id: number): Promise<User> { const request = new GetUserRequest(); request.setId(id); return new Promise((resolve, reject) => { client.getUser(request, {}, (err, response) => { err ? reject(err) : resolve(response); }); }); }

Envoy proxy configuration (brief)

# envoy.yaml core configuration http_filters: - name: envoy.filters.http.grpc_web # gRPC-Web conversion - name: envoy.filters.http.cors # CORS handling - name: envoy.filters.http.router clusters: - name: grpc_service http2_protocol_options: {} # Connect to backend over HTTP/2 load_assignment: endpoints: - endpoint: address: socket_address: { address: backend, port_value: 50051 }

Practical Conversation Example

Frontend developer

"Our backend is gRPC, so do we have to use gRPC-Web too? A REST gateway seems simpler."

Backend developer

"If you need type safety, gRPC-Web is good. With a single proto file, the frontend and backend types match, so you can develop without API documentation."

DevOps

"Don't worry, we already have Envoy in our infrastructure. We just need to add the gRPC-Web filter."

Cautions

Bidirectional streaming not supported

Due to browser limitations, client streaming and bidirectional streaming are not supported. Only server streaming is possible.

Proxy required

A proxy such as Envoy or nginx is absolutely required. This can make the infrastructure setup more complex.

Difficult to debug

Because it is a binary protocol, it is hard to read requests/responses directly in the browser developer tools.

Related Terms

Learn More