Skip to content

For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.

gRPC-Web conversion

Page as Markdown

Convert gRPC-Web requests from browser clients to gRPC for backends that speak only gRPC.

Convert gRPC-Web requests from browser clients to gRPC for backends that speak only gRPC.

About gRPC-Web conversion

Web browsers cannot send native gRPC requests, so browser clients use the gRPC-Web protocol instead. Many gRPC servers do not accept gRPC-Web requests. To reach such a backend from a browser, set the grpcWeb field on a TrafficPolicy. The gateway proxy then converts each gRPC-Web request to gRPC before forwarding the request to the backend. On the way back, the gateway proxy converts the gRPC response to gRPC-Web.

Keep the following behavior in mind:

  • gRPC-Web conversion is off by default. To enable conversion, set grpcWeb: {} in a TrafficPolicy that targets a Gateway, a listener, or a route.
  • Routes inherit the conversion setting from a broader policy, such as a Gateway-level policy. To turn off conversion for specific routes, set grpcWeb: {disable: {}} in a more specific TrafficPolicy.
  • The backend must speak gRPC. A backend that already speaks gRPC-Web does not need conversion.
  • Setting appProtocol: grpc-web on the backend Service does not enable conversion. The grpc-web value means that the backend itself already speaks gRPC-Web.
  • The gateway proxy converts only requests with a gRPC-Web content-type header. Other requests on the same route pass through unchanged.
  • Browser clients that make cross-origin calls also need a CORS policy. For more information, see CORS for browser clients.

Before you begin

  1. Follow the Get started guide to install kgateway.

  2. Follow the Sample app guide to create a gateway proxy with an HTTP listener and deploy the httpbin sample app.

  3. Get the external address of the gateway and save it in an environment variable.

    export INGRESS_GW_ADDRESS=$(kubectl get svc -n kgateway-system http -o jsonpath="{.status.loadBalancer.ingress[0]['hostname','ip']}")
    echo $INGRESS_GW_ADDRESS  

Deploy a sample gRPC service

Deploy a sample gRPC service that speaks only gRPC, not gRPC-Web. The sample service includes a yages.Echo/Ping method that takes an empty message and returns a pong message. You also create two HTTPRoutes for the service. Later in this guide, you use the grpc-web-disabled route to try out turning off conversion for one route.

  1. Deploy the gRPC echo service and the HTTPRoutes. The appProtocol: kubernetes.io/h2c setting on the Service configures the gateway proxy to connect to the backend over HTTP/2, which gRPC requires.

    kubectl apply -f- <<EOF
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: grpc-web-echo
      namespace: kgateway-system
    spec:
      selector:
        matchLabels:
          app.kubernetes.io/name: grpc-web-echo
      replicas: 1
      template:
        metadata:
          labels:
            app.kubernetes.io/name: grpc-web-echo
        spec:
          containers:
            - name: grpc-echo
              image: ghcr.io/projectcontour/yages:v0.1.0
              ports:
                - containerPort: 9000
                  protocol: TCP
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: grpc-web-echo
      namespace: kgateway-system
    spec:
      ports:
        - port: 3000
          protocol: TCP
          targetPort: 9000
          appProtocol: kubernetes.io/h2c
      selector:
        app.kubernetes.io/name: grpc-web-echo
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: grpc-web
      namespace: kgateway-system
    spec:
      parentRefs:
        - name: http
      hostnames:
        - grpc-web.example
      rules:
        - backendRefs:
            - name: grpc-web-echo
              port: 3000
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: grpc-web-disabled
      namespace: kgateway-system
    spec:
      parentRefs:
        - name: http
      hostnames:
        - grpc-web-disabled.example
      rules:
        - backendRefs:
            - name: grpc-web-echo
              port: 3000
    EOF
  2. Verify that the sample service is up and running.

    kubectl get pods -n kgateway-system -l app.kubernetes.io/name=grpc-web-echo

    Example output:

    NAME                             READY   STATUS    RESTARTS   AGE
    grpc-web-echo-6b8f9d7c5d-x2kqp   1/1     Running   0          20s
    
  3. Send a gRPC-Web request to the yages.Echo/Ping method. The request body is a gRPC-Web data frame that carries an empty message. The frame consists of a flag byte of 0 followed by a 4-byte message length of 0. The strings command prints the readable parts of the response, including the response headers that the -D - option writes.

    printf '\x00\x00\x00\x00\x00' | curl -s -D - -X POST http://$INGRESS_GW_ADDRESS:8080/yages.Echo/Ping \
      -H "host: grpc-web.example:8080" \
      -H "Content-Type: application/grpc-web+proto" \
      -H "X-Grpc-Web: 1" \
      --data-binary @- --output - | strings

    Verify that you get back a 502 HTTP response code with a protocol error reset reason. gRPC-Web conversion is not enabled yet, so the request reaches the backend unchanged. The backend accepts only gRPC requests and resets the stream.

    Example output:

    HTTP/1.1 502 Bad Gateway
    ...
    upstream connect error or disconnect/reset before headers. reset reason: protocol error
    

Enable gRPC-Web conversion for a route

Use the grpcWeb field to convert gRPC-Web requests for a single route. Use a route-level policy when only some routes on a Gateway serve browser clients.

  1. Create a TrafficPolicy that enables gRPC-Web conversion for the grpc-web HTTPRoute.

    kubectl apply -f- <<EOF
    apiVersion: gateway.kgateway.dev/v1alpha1
    kind: TrafficPolicy
    metadata:
      name: route-grpc-web
      namespace: kgateway-system
    spec:
      targetRefs:
        - group: gateway.networking.k8s.io
          kind: HTTPRoute
          name: grpc-web
      grpcWeb: {}
    EOF
    SettingDescription
    spec.targetRefsThe HTTPRoute to apply this policy to. You can also target a Gateway or a listener to enable conversion for all the routes on that Gateway or listener.
    spec.grpcWebSet to an empty object, {}, to convert gRPC-Web requests to gRPC and gRPC responses to gRPC-Web.
  2. Send the same gRPC-Web request again.

    printf '\x00\x00\x00\x00\x00' | curl -s -D - -X POST http://$INGRESS_GW_ADDRESS:8080/yages.Echo/Ping \
      -H "host: grpc-web.example:8080" \
      -H "Content-Type: application/grpc-web+proto" \
      -H "X-Grpc-Web: 1" \
      --data-binary @- --output - | strings

    Verify that you get back a 200 HTTP response code with a content-type header that starts with application/grpc-web. The response body contains the pong message and a grpc-status:0 trailer, which means that the gRPC call succeeded.

    Example output:

    HTTP/1.1 200 OK
    content-type: application/grpc-web+proto
    ...
    pong
    grpc-status:0
    

Turn off gRPC-Web conversion for a route

Use the grpcWeb.disable field to turn off conversion for specific routes. Use when a Gateway-level policy enables conversion for every route, but some routes must pass gRPC-Web requests through unchanged. For example, a route to a backend that already speaks gRPC-Web does not need conversion. For more information about how policies at different levels are merged, see Policy merging.

  1. Delete the route-level policy from the previous section. In the next step, you create a Gateway-level policy that enables conversion instead.

    kubectl delete TrafficPolicy route-grpc-web -n kgateway-system
  2. Create a TrafficPolicy that enables gRPC-Web conversion for all routes on the http Gateway. Then, create a second TrafficPolicy that turns off conversion for the grpc-web-disabled HTTPRoute.

    kubectl apply -f- <<EOF
    apiVersion: gateway.kgateway.dev/v1alpha1
    kind: TrafficPolicy
    metadata:
      name: gateway-grpc-web
      namespace: kgateway-system
    spec:
      targetRefs:
        - group: gateway.networking.k8s.io
          kind: Gateway
          name: http
      grpcWeb: {}
    ---
    apiVersion: gateway.kgateway.dev/v1alpha1
    kind: TrafficPolicy
    metadata:
      name: route-disable-grpc-web
      namespace: kgateway-system
    spec:
      targetRefs:
        - group: gateway.networking.k8s.io
          kind: HTTPRoute
          name: grpc-web-disabled
      grpcWeb:
        disable: {}
    EOF
    SettingDescription
    gateway-grpc-web policyTargets the http Gateway. The grpcWeb: {} setting enables gRPC-Web conversion for all routes on the Gateway.
    route-disable-grpc-web policyTargets the grpc-web-disabled HTTPRoute. The grpcWeb.disable: {} setting turns off the conversion that the route inherits from the Gateway-level policy.
  3. Send a gRPC-Web request to the grpc-web.example host.

    printf '\x00\x00\x00\x00\x00' | curl -s -D - -X POST http://$INGRESS_GW_ADDRESS:8080/yages.Echo/Ping \
      -H "host: grpc-web.example:8080" \
      -H "Content-Type: application/grpc-web+proto" \
      -H "X-Grpc-Web: 1" \
      --data-binary @- --output - | strings

    Verify that you get back a 200 HTTP response code with the pong message and a grpc-status:0 trailer, the same as in the previous section. The Gateway-level policy now enables the conversion for the grpc-web HTTPRoute.

  4. Send a gRPC-Web request to the grpc-web-disabled.example host.

    printf '\x00\x00\x00\x00\x00' | curl -s -D - -X POST http://$INGRESS_GW_ADDRESS:8080/yages.Echo/Ping \
      -H "host: grpc-web-disabled.example:8080" \
      -H "Content-Type: application/grpc-web+proto" \
      -H "X-Grpc-Web: 1" \
      --data-binary @- --output - | strings

    Verify that you get back a 502 HTTP response code with a protocol error reset reason. The route-level policy turns off the conversion, so the request reaches the backend unchanged.

    Example output:

    HTTP/1.1 502 Bad Gateway
    ...
    upstream connect error or disconnect/reset before headers. reset reason: protocol error
    

CORS for browser clients

A browser client that is served from a different origin than the gRPC-Web service sends cross-origin requests. The browser blocks such requests unless the gateway proxy returns the required CORS headers. Enabling gRPC-Web conversion does not add any CORS settings for you. In your CORS policy, allow the following headers in addition to the headers that your app needs:

  • Allow the content-type, x-grpc-web, and x-user-agent request headers.
  • Expose the grpc-status and grpc-message response headers so that the browser client can read the result of the gRPC call.

The following example TrafficPolicy enables gRPC-Web conversion and CORS together for the grpc-web HTTPRoute. Replace https://app.example.com with the origin that serves your browser client. For more information about CORS settings, see CORS.

apiVersion: gateway.kgateway.dev/v1alpha1
kind: TrafficPolicy
metadata:
  name: route-grpc-web-cors
  namespace: kgateway-system
spec:
  targetRefs:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      name: grpc-web
  grpcWeb: {}
  cors:
    allowOrigins:
      - "https://app.example.com"
    allowMethods:
      - "POST"
      - "OPTIONS"
    allowHeaders:
      - "content-type"
      - "x-grpc-web"
      - "x-user-agent"
    exposeHeaders:
      - "grpc-status"
      - "grpc-message"
    maxAge: 86400

Cleanup

You can remove the resources that you created in this guide.
kubectl delete TrafficPolicy route-grpc-web gateway-grpc-web route-disable-grpc-web -n kgateway-system --ignore-not-found
kubectl delete httproute grpc-web grpc-web-disabled -n kgateway-system
kubectl delete service grpc-web-echo -n kgateway-system
kubectl delete deployment grpc-web-echo -n kgateway-system
Was this page helpful?