gRPC behind a Next.js frontend
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 and gRPC services.
Draft
1. Why does the browser not call the gRPC service?
Section titled “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
Section titled “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
Section titled “Do this”- Call the services only from server code: Server Components, Server Actions and Route Handlers.
- Keep the session in an
httpOnlycookie and the tokens on the server (Next.js next to the service, step 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
Section titled “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?
Section titled “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.
npx buf generateWhat’s going on
Section titled “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
Section titled “Do this”-
Add
@bufbuild/bufand@bufbuild/protoc-gen-esas exact dev dependencies, and@bufbuild/protobuf,@connectrpc/connectand@connectrpc/connect-nodeas dependencies. -
Add a
buf.gen.yamlto the frontend that reads the contract project in the same repository, here the vertical’sapi/next to itsweb/(Monorepos, step 2):version: v2inputs:- directory: ../apiplugins:- local: protoc-gen-esout: src/genopt: target=tsinclude_imports: trueclean: trueinclude_importsalso generates the files the contract imports, such as protovalidate’s. In a project of one service, with the contract in its ownsrc/main/protoandbuf.yamlat the root, the frontend infrontends/webreadsdirectory: ../..instead. -
Commit
src/gen. In CI, runnpx buf generateand fail whengit status --porcelain --untracked-files=all -- src/genprints 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). Where the CI container has no git, generate into another folder withnpx buf generate -o <folder>and compare it withdiff -r. -
Do not set
import_extension=js: Next.js does not resolve a.jsimport to a.tsfile.
When this is not for you
Section titled “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?
Section titled “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.
const transport = createGrpcTransport({ baseUrl: process.env.ORDERS_URL!, defaultTimeoutMs: 2000 });What’s going on
Section titled “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
Section titled “Do this”-
Put the clients in a
server-onlymodule, so importing it from a Client Component fails the build: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;} -
Export functions like
getOrderthat check the session and return plain data, the data access layer Next.js recommends. Pages and actions call those, never the client. -
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). -
Keep the default Node.js runtime: the transport needs
node:http2, which the Edge runtime does not have.
When this is not for you
Section titled “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?
Section titled “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
Section titled “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). A call can
also be cancelled with an AbortSignal.
Do this
Section titled “Do this”- Set
defaultTimeoutMson each transport from the slowest normal answer of that service, with a margin. - Give a slower method its own
timeoutMson the call instead of raising the default for all. - Keep the timeout below the time the user will wait: a page that times out can still show what it has.
- In a Route Handler, pass
request.signalas the call’ssignal, so a closed tab cancels the call.
When this is not for you
Section titled “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?
Section titled “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
Section titled “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
Section titled “Do this”-
Generate the
google.rpcerror types once, from Buf’sgoogleapismodule, sofindDetailscan read them. -
In each Server Action, catch the call, match on the reason and return a message for the user:
'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;}} -
Let unexpected errors reach the error page; log them on the server with the trace ID.
-
On
Unauthenticated, send the user to the login page. Callredirect()outside thetry, because it works by throwing.
When this is not for you
Section titled “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?
Section titled “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
Section titled “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
Section titled “Do this”-
Stream from a Route Handler, read one event per
pulland passrequest.signal: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: 0turns off the default deadline for this call; the service ends the stream after a fixed time (gRPC services, step 7). -
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. -
Set a request timeout for the stream’s route on the gateway, such as
timeouts.requeston the Gateway APIHTTPRoute, longer than the stream lives. -
In the browser, reconnect with a growing, random delay, and start from the last event the page saw.
When this is not for you
Section titled “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?
Section titled “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
Section titled “What’s going on”The Kubernetes Service balances connections, not calls, the same problem as between Java services
(gRPC services, step 9). 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
Section titled “Do this”- 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. - Without a mesh, set
spring.grpc.server.keepalive.connection.max-ageon the service, for example to a few minutes, so connections move between pods. - Run more than one Next.js pod. Each one has its own connection.
- Watch the call count per service pod: it should be even.
When this is not for you
Section titled “When this is not for you”- The service runs one pod: there is nothing to balance yet. Set
max-ageanyway, 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?
Section titled “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.
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
Section titled “What’s going on”The Next.js server starts a trace for each request
(Next.js next to the service, step 8). 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
Section titled “Do this”- Add the interceptor above to every transport with
interceptors: [tracing]. - Check in your tracing backend that a page view and the service’s spans share one trace ID.
When this is not for you
Section titled “When this is not for you”- The app already has instrumentation that covers Node’s
http2module: 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
Section titled “Put it all together”This is where each step lands.
In the frontend
Section titled “In the frontend”buf.gen.yamlpointing at the contract,protoc-gen-esandbufpinned,src/gencommitted and checked in CI (step 2).- One
server-onlymodule per service with one transport,defaultTimeoutMsand 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
ErrorInforeason (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
Section titled “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-ageon 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
Section titled “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.
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.
GWEB-04 Every transport sets defaultTimeoutMs; Route Handlers pass request.signal to their calls.
GWEB-08 Every transport has an interceptor that injects the trace context into the call headers.
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.
Deployment prerequisites
GWEB-01 The browser never calls a gRPC service; only Next.js server code does, and the services have no public route.
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.
GWEB-07 Frontend calls are balanced per request by a mesh, or the services set keepalive.connection.max-age.
References
Section titled “References”Official documentation
The full list is on Reference docs.
- gRPC-Web roadmap (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 (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 (not in the baseline yet). MAX_CONNECTION_AGE makes clients reconnect so new pods get calls.
- Linkerd 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 (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 (not in the baseline yet). The original description of the backend for frontend pattern.
- Next.js: 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 (not in the baseline yet). The server-only data access layer that checks the session and returns plain data.
- Next.js: 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 (not in the baseline yet). Route Handlers, including streaming responses.
- Next.js: self-hosting (not in the baseline yet). Streaming behind a proxy and the X-Accel-Buffering header.
- Next.js: route segment config (not in the baseline yet). The runtime option and its Node.js default.
- Next.js: OpenTelemetry (not in the baseline yet). The spans Next.js creates on its own, fetch included.
- Connect for Node.js: using clients (not in the baseline yet). createGrpcTransport, which speaks gRPC over HTTP/2 from Node.js.
- Connect: choosing a protocol (not in the baseline yet). Connect, gRPC and gRPC-Web transports and when each one fits.
- Connect protocol reference (not in the baseline yet). The Connect protocol: JSON over POST and GET for methods without side effects.
- Connect: generating code (not in the baseline yet). buf generate with the protoc-gen-es plugin for TypeScript.
- Connect: errors (not in the baseline yet). ConnectError, its code and findDetails for google.rpc error details.
- Connect: interceptors (not in the baseline yet). Interceptors that add headers to every call.
- Connect: 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 (not in the baseline yet). Maintainers on how the Node transport holds its HTTP/2 connection.
- connect-es issue 523: OpenTelemetry support (not in the baseline yet). Open request for an official OpenTelemetry integration.
- Protobuf-ES (not in the baseline yet). The TypeScript Protocol Buffers runtime and the protoc-gen-es plugin.
- buf.gen.yaml v2 configuration (not in the baseline yet). Inputs, local plugins, include_imports and clean for buf generate.
- Spring gRPC issue 427: gRPC-Web (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 (not in the baseline yet). Lets a Connect client, such as a browser, call a gRPC server through Envoy.
- Envoy Gateway: HTTP request timeouts (not in the baseline yet). The 15 second default route timeout and how to change it per route.
- Istio: protocol selection (not in the baseline yet). Mark a port with appProtocol grpc so Istio balances per request.
- MDN: using server-sent events (not in the baseline yet). The event stream format, comments as heartbeats and EventSource reconnects.