> Every Pyahu Initializer guide: https://initializer.pyahu.io/llms.txt. Every Pyahu Community project: https://pyahu.io/llms.txt.

# gRPC behind a Next.js frontend

Let the Next.js server call your gRPC services with typed clients, the user's token, deadlines, readable errors and live updates, while the browser never speaks gRPC.

On the web: https://initializer.pyahu.io/guides/grpc-frontend/. Written for baseline v0.1-b10: Java 25, Spring Boot 4.2.0.

**Draft:** no step of this guide is tested here yet.

The orders service speaks gRPC and the frontend team wants to call it from the browser. They add a proxy, open
CORS, put the access token in JavaScript and copy the generated TypeScript into three apps. A month later one copy
is stale, a live order page leaks a stream every time someone closes the tab, and users see
`[internal] order 42 not found` when a call fails.

This guide puts the Next.js server between the browser and the services. The browser talks to Next.js; only the
Next.js server speaks gRPC, with generated clients, the user's token, a deadline on every call and errors turned
into messages a person can read. It builds on [Next.js next to the service](nextjs.md) and
[gRPC services](grpc.md).

## What you'll learn

1. Why does the browser not call the gRPC service?
2. How does the frontend get typed clients?
3. Where is the client created and how does it carry the token?
4. How long does a page wait for the service?
5. How do I show a gRPC error to the user?
6. How do I push live updates to the browser?
7. Why do the frontend's calls land on one pod?
8. How do I follow a page into the service's trace?

## 1. Why does the browser not call the gRPC service?

**In short:** because the Next.js server can do it better. It calls the services over gRPC and keeps the tokens;
the browser only talks to Next.js, which is the backend for frontend pattern.

### What's going on

A browser cannot send gRPC itself. gRPC-Web and the Connect protocol work around that, but both need something in
front of a Spring service: neither gRPC Java nor Spring gRPC speaks them, so an Envoy filter or a different server
has to translate. Browsers also cannot stream from the client, and the gRPC-Web JavaScript library gets no new
features.

The bigger reason is the token. A browser that calls the service must hold the access token where scripts can read
it. The IETF's guidance for browser-based apps, RFC 10017, ranks a backend for frontend first, because then no
token is in the browser at all. Next.js supports this pattern directly: Server Components read data, Server Actions
change it and both run on the server.

### Do this

1. Call the services only from server code: Server Components, Server Actions and Route Handlers.
2. Keep the session in an `httpOnly` cookie and the tokens on the server
   ([Next.js next to the service, step 3](https://initializer.pyahu.io/guides/nextjs/#next-auth)).
3. Reach the services by their cluster names. They need no public route, no CORS and no gRPC-Web proxy.

### When this is not for you

- A public, read-only API that a CDN should cache, with no user token: the Connect protocol can serve it to the
  browser as plain HTTP GET through Envoy's Connect bridge.
- A frontend without a server, such as a static site: it has to call through a gateway that translates, and the
  token lives in the browser. Prefer adding a server.

## 2. How does the frontend get typed clients?

**In short:** generate TypeScript from the service's `.proto` files with `buf` and `protoc-gen-es`, pinned in
`package.json`, and let CI fail when the generated files are stale.

```sh
npx buf generate
```

### What's going on

`protoc-gen-es`, from Protobuf-ES, writes the message types and the service descriptions; Connect's client uses
them directly. In version 2 there is no separate Connect generator any more.

Copying the generated files from one app to the next, or generating them with a plugin version nobody pinned, gives
you copies that drift. The first sign is a field that is always empty.

### Do this

1. Add `@bufbuild/buf` and `@bufbuild/protoc-gen-es` as exact dev dependencies, and `@bufbuild/protobuf`,
   `@connectrpc/connect` and `@connectrpc/connect-node` as dependencies.
2. Add a `buf.gen.yaml` to the frontend that reads the contract project in the same repository, here the
   vertical's `api/` next to its `web/` ([Monorepos, step 2](https://initializer.pyahu.io/guides/monorepo/#mono-layout)):

   ```yaml
   version: v2
   inputs:
     - directory: ../api
   plugins:
     - local: protoc-gen-es
       out: src/gen
       opt: target=ts
       include_imports: true
   clean: true
   ```

   `include_imports` also generates the files the contract imports, such as protovalidate's. In a project of one
   service, with the contract in its own `src/main/proto` and `buf.yaml` at the root, the frontend in
   `frontends/web` reads `directory: ../..` instead.
3. Commit `src/gen`. In CI, run `npx buf generate` and fail when
   `git status --porcelain --untracked-files=all -- src/gen` prints anything, so a stale or missing file fails the
   build, the same rule as for OpenAPI types
   ([Next.js next to the service, step 2](https://initializer.pyahu.io/guides/nextjs/#next-typed-client)). Where the CI container has no git,
   generate into another folder with `npx buf generate -o <folder>` and compare it with `diff -r`.
4. Do not set `import_extension=js`: Next.js does not resolve a `.js` import to a `.ts` file.

### When this is not for you

- The contract is published to the Buf Schema Registry: install the generated npm package from there instead of
  generating it yourself.
- The frontend lives in another repository: generate from a tagged version of the contract, never from a copy.

## 3. Where is the client created and how does it carry the token?

**In short:** create one transport per service, once, in a `server-only` module, and pass the user's token with
each call.

```ts
const transport = createGrpcTransport({ baseUrl: process.env.ORDERS_URL!, defaultTimeoutMs: 2000 });
```

### What's going on

`createGrpcTransport`, from `@connectrpc/connect-node`, speaks plain gRPC over HTTP/2 to the service. Each transport
opens and keeps one connection. A transport created inside every request pays a new connection for every call,
and the old ones stay open until they time out.

The transport is shared by every user, so the token cannot live in it. It belongs to the call.

### Do this

1. Put the clients in a `server-only` module, so importing it from a Client Component fails the build:

   ```ts
   import 'server-only';
   import { createClient } from '@connectrpc/connect';
   import { createGrpcTransport } from '@connectrpc/connect-node';
   import { OrderService } from '@/gen/shop/orders/v1/order_service_pb';
   import { accessToken } from './session';

   const orders = createClient(OrderService, createGrpcTransport({
     baseUrl: process.env.ORDERS_URL ?? 'http://localhost:9090',
     defaultTimeoutMs: 2000,
   }));

   export async function getOrder(orderId: string) {
     const headers = { authorization: `Bearer ${await accessToken()}` };
     const { order } = await orders.getOrder({ orderId }, { headers });
     return order;
   }
   ```

2. Export functions like `getOrder` that check the session and return plain data, the data access layer Next.js
   recommends. Pages and actions call those, never the client.
3. Read the service URL from a server environment variable at run time, never a `NEXT_PUBLIC_` one
   ([Next.js next to the service, step 4](https://initializer.pyahu.io/guides/nextjs/#next-env)).
4. Keep the default Node.js runtime: the transport needs `node:http2`, which the Edge runtime does not have.

### When this is not for you

- A page calls a service without a user, such as a public catalogue: leave out the token, and let the service
  allow that method without one.
- A call the Next.js server makes for itself, such as warming a cache at start: use its own client credentials
  token, not a user's.

## 4. How long does a page wait for the service?

**In short:** set `defaultTimeoutMs` on every transport. It reaches the service as the gRPC deadline, so both sides
stop at the same time.

### What's going on

Without a timeout, a page waits as long as the service does. The user sees a spinner, the Next.js server holds the
request, and the service may still be working on an answer nobody will read.

Connect sends the timeout as the `grpc-timeout` header, so the Java service sees it as the call's deadline and
passes the time left to the services it calls ([gRPC services, step 5](https://initializer.pyahu.io/guides/grpc/#grpc-deadlines)). A call can
also be cancelled with an `AbortSignal`.

### Do this

1. Set `defaultTimeoutMs` on each transport from the slowest normal answer of that service, with a margin.
2. Give a slower method its own `timeoutMs` on the call instead of raising the default for all.
3. Keep the timeout below the time the user will wait: a page that times out can still show what it has.
4. In a Route Handler, pass `request.signal` as the call's `signal`, so a closed tab cancels the call.

### When this is not for you

- A stream that stays open on purpose: see step 6.
- A call that starts work the user does not wait for, such as an export: return at once and let the page poll or
  stream its progress.

## 5. How do I show a gRPC error to the user?

**In short:** read the status code and the `ErrorInfo` reason from the `ConnectError`, turn the expected ones into a
message, and return it from Server Actions as a value. Never show the raw message.

### What's going on

A failed call throws a `ConnectError` with a `code`, a `rawMessage` and the error details the service sent. Its
`message` starts with the code in brackets, like `[not_found] ...`, which is why users end up seeing it.

Next.js hides the message of errors thrown in Server Components in production and shows the nearest error page.
For Server Actions, its docs say to return expected errors as values instead of throwing them, and to read them
with `useActionState`.

### Do this

1. Generate the `google.rpc` error types once, from Buf's `googleapis` module, so `findDetails` can read them.
2. In each Server Action, catch the call, match on the reason and return a message for the user:

   ```ts
   'use server';

   export async function cancelOrder(_: State, form: FormData): Promise<State> {
     try {
       await cancel(String(form.get('orderId')));
       return { error: null };
     } catch (cause) {
       const error = ConnectError.from(cause);
       const reason = error.findDetails(ErrorInfoSchema)[0]?.reason;
       if (reason === 'ORDER_ALREADY_SHIPPED') return { error: 'This order has already shipped.' };
       if (error.code === Code.NotFound) return { error: 'This order no longer exists.' };
       throw cause;
     }
   }
   ```

3. Let unexpected errors reach the error page; log them on the server with the trace ID.
4. On `Unauthenticated`, send the user to the login page. Call `redirect()` outside the `try`, because it works by
   throwing.

### When this is not for you

- A Server Component that cannot show anything useful without the data: let the error page handle it.
- Validation errors from protovalidate: read the violations from the details and show each one next to its field.

## 6. How do I push live updates to the browser?

**In short:** read the gRPC server stream in a Route Handler and send it on as server-sent events, one event at a
time as the browser reads them. Pass the request's signal and raise the gateway's route timeout for that path.

### What's going on

The browser opens an `EventSource` to the Route Handler, and the Route Handler holds a server stream to the service.
When the user closes the tab, the request's signal fires; if nobody passes it on, the gRPC stream keeps running and
streams pile up until a pod runs out of threads or memory.

A browser on a slow connection reads more slowly than the service writes. If the Route Handler keeps reading the
gRPC stream anyway, the events queue up in the Next.js server's memory. Reading the next event only when the
browser asks for one keeps gRPC's flow control working end to end.

Gateways close requests that take too long. Envoy's default route timeout is 15 seconds, so a live page that
works locally disconnects every 15 seconds in production, and every reconnect opens a new stream.

### Do this

1. Stream from a Route Handler, read one event per `pull` and pass `request.signal`:

   ```ts
   export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
     const { id } = await params;
     const headers = { authorization: `Bearer ${await accessToken()}` };
     const stop = new AbortController();
     const signal = AbortSignal.any([request.signal, stop.signal]);
     const events = orders.watchOrder({ orderId: id }, { headers, signal, timeoutMs: 0 })[Symbol.asyncIterator]();
     const encoder = new TextEncoder();
     const body = new ReadableStream({
       async pull(controller) {
         const { value, done } = await events.next();
         if (done) return controller.close();
         controller.enqueue(encoder.encode(`data: ${JSON.stringify(toJson(WatchOrderResponseSchema, value))}\n\n`));
       },
       cancel() {
         stop.abort();
       },
     });
     return new Response(body, {
       headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no' },
     });
   }
   ```

   `timeoutMs: 0` turns off the default deadline for this call; the service ends the stream after a fixed time
   ([gRPC services, step 7](https://initializer.pyahu.io/guides/grpc/#grpc-streaming)).
2. When events can be minutes apart, let the service send a heartbeat message on the stream and forward it as a
   comment line, `: ping`, so idle timers along the way do not close the connection.
3. Set a request timeout for the stream's route on the gateway, such as `timeouts.request` on the Gateway API
   `HTTPRoute`, longer than the stream lives.
4. In the browser, reconnect with a growing, random delay, and start from the last event the page saw.

### When this is not for you

- The page can live with data a few seconds old: poll with a Server Component refresh instead of streaming.
- The browser must send messages too, such as a chat: use a WebSocket, since no browser can stream gRPC to the
  server.

## 7. Why do the frontend's calls land on one pod?

**In short:** each transport keeps one HTTP/2 connection, so every Next.js pod sends all its calls to one service
pod. Balance per request with a service mesh, or make the service close old connections.

### What's going on

The Kubernetes Service balances connections, not calls, the same problem as between Java services
([gRPC services, step 9](https://initializer.pyahu.io/guides/grpc/#grpc-load-balancing)). The Java client fixes it with `round_robin` over a
headless Service. The Connect transport cannot: it has no name resolver or load balancer, so it opens one
connection to one address.

When the service sends a GOAWAY because a connection reached its maximum age, the transport finishes the calls in
flight and opens a new connection, which may land on another pod. That spreads the load over time, not per call.

### Do this

1. In a service mesh such as Linkerd, or Istio with a sidecar or a waypoint, let the mesh balance each request. In
   Istio, mark the port with `appProtocol: grpc`.
2. Without a mesh, set `spring.grpc.server.keepalive.connection.max-age` on the service, for example to a few
   minutes, so connections move between pods.
3. Run more than one Next.js pod. Each one has its own connection.
4. Watch the call count per service pod: it should be even.

### When this is not for you

- The service runs one pod: there is nothing to balance yet. Set `max-age` anyway, so the first scale up works.
- Istio in ambient mode without a waypoint: its node proxy works on connections only, so calls stay pinned like
  with a plain Service.

## 8. How do I follow a page into the service's trace?

**In short:** add an interceptor that writes the current trace context into the call's headers. Connect has no
official OpenTelemetry package, the usual HTTP instrumentation does not see HTTP/2 calls and a mesh cannot do it
for you.

```ts
const tracing: Interceptor = (next) => (req) => {
  propagation.inject(context.active(), req.header, { set: (header, key, value) => header.set(key, value) });
  return next(req);
};
```

### What's going on

The Next.js server starts a trace for each request
([Next.js next to the service, step 8](https://initializer.pyahu.io/guides/nextjs/#next-tracing)). Its built-in spans cover `fetch`. The
Connect transport uses Node's `http2` module, which the OpenTelemetry HTTP instrumentation does not patch, so the
call leaves without a `traceparent` header and the service starts a new, unrelated trace. A service mesh does not
fix this: its proxy sees the call leave but cannot tell which incoming request caused it, so the application has to
pass the context on.

### Do this

1. Add the interceptor above to every transport with `interceptors: [tracing]`.
2. Check in your tracing backend that a page view and the service's spans share one trace ID.

### When this is not for you

- The app already has instrumentation that covers Node's `http2` module: check that the trace is joined before
  adding the interceptor, so the headers are not written twice.
- You do not collect traces yet: add the interceptor anyway; it costs nothing until a tracer is configured.

## Put it all together

This is where each step lands.

### In the frontend

- `buf.gen.yaml` pointing at the contract, `protoc-gen-es` and `buf` pinned, `src/gen` committed and checked in CI
  (step 2).
- One `server-only` module per service with one transport, `defaultTimeoutMs` and the tracing interceptor, and
  functions that pass the user's token per call (steps 3, 4 and 8).
- Server Actions that return expected errors as values, matched on the `ErrorInfo` reason (step 5).
- Route Handlers that turn server streams into server-sent events, one event per read, with the request's signal
  (step 6).

**Check it:** make a service method sleep longer than `defaultTimeoutMs` and load its page: the call fails with
`DeadlineExceeded` at the timeout, and the service sees the deadline on the incoming call. Close a live page: the
service's stream handler sees the cancel at once.

### In the cluster

- No public route to the gRPC services (step 1).
- A longer route timeout for the streaming paths on the gateway (step 6).
- A mesh that balances per request, or `max-age` on the services (step 7).

**Check it:** `kubectl get httproute,grpcroute -A` lists no route to a gRPC service's port; only the frontend has
one.

## Checklist

### Generated configuration

- **GWEB-02** TypeScript clients come from buf generate with a pinned protoc-gen-es; CI fails when the committed output is stale. (step 2; when api: grpc; frontend: nextjs)
- **GWEB-03** One transport per service lives in a server-only module; the user's token is passed with each call, never stored in the transport. (step 3; when api: grpc; frontend: nextjs)
- **GWEB-04** Every transport sets defaultTimeoutMs; Route Handlers pass request.signal to their calls. (step 4; when api: grpc; frontend: nextjs)
- **GWEB-08** Every transport has an interceptor that injects the trace context into the call headers. (step 8; when api: grpc; frontend: nextjs)

### Verified behaviour

- **GWEB-05** Server Actions return expected gRPC errors as values, matched on code and ErrorInfo reason; users never see a raw error message. (step 5; when api: grpc; frontend: nextjs)

### Deployment prerequisites

- **GWEB-01** The browser never calls a gRPC service; only Next.js server code does, and the services have no public route. (step 1; when api: grpc; frontend: nextjs)
- **GWEB-06** Server streams reach the browser as server-sent events with the request signal passed, a heartbeat and a longer route timeout on the gateway. (step 6; when api: grpc; frontend: nextjs)
- **GWEB-07** Frontend calls are balanced per request by a mesh, or the services set keepalive.connection.max-age. (step 7; when api: grpc; frontend: nextjs)

## References

- [gRPC-Web roadmap](https://github.com/grpc/grpc-web/blob/master/doc/roadmap.md) (not in the baseline yet): gRPC-Web plans no new features; why browsers need another path to gRPC services.
- [gRPC load balancing on Kubernetes without tears](https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears/) (not in the baseline yet): Why a cluster IP Service pins gRPC calls to one pod and how clients or a mesh spread them.
- [gRPC proposal A9: server-side connection management](https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md) (not in the baseline yet): MAX_CONNECTION_AGE makes clients reconnect so new pods get calls.
- [Linkerd load balancing](https://linkerd.io/2-edge/features/load-balancing/) (not in the baseline yet): A mesh that balances each gRPC request across pods with no client configuration.
- [RFC 10017: OAuth 2.0 for browser-based applications](https://www.rfc-editor.org/rfc/rfc10017.html) (not in the baseline yet): The IETF best practice that ranks a backend for frontend first, with no token in the browser.
- [Sam Newman: backends for frontends](https://samnewman.io/patterns/architectural/bff/) (not in the baseline yet): The original description of the backend for frontend pattern.
- [Next.js: backend for frontend](https://nextjs.org/docs/app/guides/backend-for-frontend) (not in the baseline yet): How Next.js serves as a backend for frontend: Server Components read, Server Actions write.
- [Next.js: data security](https://nextjs.org/docs/app/guides/data-security) (not in the baseline yet): The server-only data access layer that checks the session and returns plain data.
- [Next.js: error handling](https://nextjs.org/docs/app/getting-started/error-handling) (not in the baseline yet): Expected errors returned as values from Server Actions; uncaught ones go to the error page.
- [Next.js: route.js](https://nextjs.org/docs/app/api-reference/file-conventions/route) (not in the baseline yet): Route Handlers, including streaming responses.
- [Next.js: self-hosting](https://nextjs.org/docs/app/guides/self-hosting) (not in the baseline yet): Streaming behind a proxy and the X-Accel-Buffering header.
- [Next.js: route segment config](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config) (not in the baseline yet): The runtime option and its Node.js default.
- [Next.js: OpenTelemetry](https://nextjs.org/docs/app/guides/open-telemetry) (not in the baseline yet): The spans Next.js creates on its own, fetch included.
- [Connect for Node.js: using clients](https://connectrpc.com/docs/node/using-clients/) (not in the baseline yet): createGrpcTransport, which speaks gRPC over HTTP/2 from Node.js.
- [Connect: choosing a protocol](https://connectrpc.com/docs/web/choosing-a-protocol/) (not in the baseline yet): Connect, gRPC and gRPC-Web transports and when each one fits.
- [Connect protocol reference](https://connectrpc.com/docs/protocol/) (not in the baseline yet): The Connect protocol: JSON over POST and GET for methods without side effects.
- [Connect: generating code](https://connectrpc.com/docs/web/generating-code/) (not in the baseline yet): buf generate with the protoc-gen-es plugin for TypeScript.
- [Connect: errors](https://connectrpc.com/docs/web/errors/) (not in the baseline yet): ConnectError, its code and findDetails for google.rpc error details.
- [Connect: interceptors](https://connectrpc.com/docs/web/interceptors/) (not in the baseline yet): Interceptors that add headers to every call.
- [Connect: cancellation and timeouts](https://connectrpc.com/docs/web/cancellation-and-timeouts/) (not in the baseline yet): Timeouts sent as the gRPC deadline and cancellation with an AbortSignal.
- [connect-es issue 1276: transports and connections](https://github.com/connectrpc/connect-es/issues/1276) (not in the baseline yet): Maintainers on how the Node transport holds its HTTP/2 connection.
- [connect-es issue 523: OpenTelemetry support](https://github.com/connectrpc/connect-es/issues/523) (not in the baseline yet): Open request for an official OpenTelemetry integration.
- [Protobuf-ES](https://github.com/bufbuild/protobuf-es) (not in the baseline yet): The TypeScript Protocol Buffers runtime and the protoc-gen-es plugin.
- [buf.gen.yaml v2 configuration](https://buf.build/docs/configuration/v2/buf-gen-yaml/) (not in the baseline yet): Inputs, local plugins, include_imports and clean for buf generate.
- [Spring gRPC issue 427: gRPC-Web](https://github.com/spring-projects/spring-grpc/issues/427) (not in the baseline yet): Open request for gRPC-Web in Spring gRPC; grpc-java has no support for it.
- [Envoy Connect-gRPC bridge filter](https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/connect_grpc_bridge_filter) (not in the baseline yet): Lets a Connect client, such as a browser, call a gRPC server through Envoy.
- [Envoy Gateway: HTTP request timeouts](https://gateway.envoyproxy.io/docs/tasks/traffic/http-timeouts/) (not in the baseline yet): The 15 second default route timeout and how to change it per route.
- [Istio: protocol selection](https://istio.io/latest/docs/ops/configuration/traffic-management/protocol-selection/) (not in the baseline yet): Mark a port with appProtocol grpc so Istio balances per request.
- [MDN: using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (not in the baseline yet): The event stream format, comments as heartbeats and EventSource reconnects.
