How to integrate GRPC API in React app? #198375
-
🏷️ Discussion TypeQuestion 💬 Feature/Topic AreaAPI BodyCan anyone teach me how to integrate a gRPC API into a React application, including setting up gRPC-Web, configuring client services, handling requests and responses, and connecting frontend components to backend gRPC endpoints? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
How to Integrate a gRPC API in a React ApplicationIntegrating a gRPC API into a React application differs from consuming a traditional REST API because browsers cannot communicate directly with standard gRPC services. To bridge this gap, developers typically use gRPC-Web, which enables React applications to communicate with gRPC servers through a proxy such as Envoy. What is gRPC?gRPC is a high-performance Remote Procedure Call (RPC) framework developed by Google. It uses HTTP/2 and Protocol Buffers (protobuf) to provide efficient, strongly typed communication between services. Compared to REST APIs, gRPC offers:
Typical ArchitectureA typical React and gRPC setup consists of:
The React application sends requests using gRPC-Web, Envoy translates them into standard gRPC requests, and the backend service processes them. Step 1: Define a Protocol BufferThe API contract is defined using a Example:
Step 2: Generate Client CodeUsing the Protocol Buffer compiler ( These generated files provide:
Step 3: Configure a gRPC ClientCreate a client instance that points to the gRPC-Web endpoint exposed by Envoy. The client becomes the central object used to communicate with backend services throughout the application. Step 4: Create an API Service LayerInstead of calling the generated client directly inside React components, create a service layer that wraps gRPC calls. Benefits
Example service methods:
Step 5: Use the Service Inside React ComponentsReact components can call the API service functions using hooks such as Typical flow:
TypeScript SupportgRPC integrates well with TypeScript because the generated code includes type definitions. Advantages
AuthenticationAuthentication tokens such as JWTs can be passed through gRPC metadata. Common use cases:
Error HandlinggRPC returns structured error codes that can be handled on the frontend. Common error codes include:
Applications should display meaningful error messages and handle failures gracefully. React Query IntegrationFor production applications, integrating gRPC with React Query is highly recommended. Benefits
This significantly improves application performance and user experience. Streaming SupportOne of gRPC's biggest advantages is streaming. Supported communication patterns:
In browser environments using gRPC-Web, unary requests and server-streaming are the most commonly supported. Streaming is useful for:
Recommended Project StructureKeeping gRPC logic isolated makes the application easier to maintain. Best Practices
When to Use gRPCUse gRPC when:
Use REST when:
Typical Production StackA modern production setup often includes:
This architecture provides excellent performance, scalability, and maintainability for modern web applications. |
Beta Was this translation helpful? Give feedback.
-
|
Hey, Alex Here is a sample code that shows making a simple gRPC client. `const GRPC_METHODS = Object.values(GRPC_SERVICES).flatMap((service) => export type GRPCServiceType = keyof typeof GRPC_SERVICES; const header: Interceptor = (next) => async (req) => { const serviceName = req?.service?.typeName; logger.log( return await next(req) const transport = createConnectTransport({ export function grpcClient(service: T): Client { |
Beta Was this translation helpful? Give feedback.
-
|
@it-mario Can you also show me how to use this gRPC client? |
Beta Was this translation helpful? Give feedback.
Hey, Alex
Here is a sample code that shows making a simple gRPC client.
`const GRPC_METHODS = Object.values(GRPC_SERVICES).flatMap((service) =>
Object.keys(service.methods)
) as (keyof (typeof GRPC_SERVICES)[keyof typeof GRPC_SERVICES]['methods'])[];
export type GRPCServiceType = keyof typeof GRPC_SERVICES;
export type GRPCMethodType = (typeof GRPC_METHODS)[number];
const header: Interceptor = (next) => async (req) => {
const zhbr = getAccessToken();
if (zhbr !== null) {
req.header.set('Authorization', 'Bearer ' + zhbr);
}
const serviceName = req?.service?.typeName;
const methodName = req?.method?.name;
logger.log(
[HTTP][REQ][${methodName}], req.url, {request: req,
});
return await next(…