gRPC-Web
This feature is experimental.
The Java/Scala API’s to enable this feature may still change in further versions of Pekko gRPC, and future versions of this feature may not work with services generated with older versions of Pekko gRPC.
There may be missing features and bugs in the current implementation. If you encounter any, you are welcome to share a reproducer in our issue tracker.
gRPC cannot be used directly from the browser because of limitations on the amount of control the Javascript code has on the behavior of the browser.
The gRPC-Web protocol was designed to be usable from a browser, but be easily translatable into native gRPC calls.
The most common deployment model of gRPC-Web is to use a proxy such as Envoy to translate between the gRPC-Web frontend and a native gRPC back-end. This is a great choice with Pekko gRPC services.
However, in some situations it may be operationally simpler if your service supports gRPC-Web directly. This is now possible with Pekko gRPC as well.
To serve a gRPC service with Pekko gRPC, it is recommended to serve the native gRPC protocol on a different port than gRPC-Web, as the two protocols will likely require a different security story. You can use WebHandler.grpcWebHandler
WebHandler.grpcWebHandler
to serve your gRPC-Web endpoint with basic CORS infrastructure in place. To use CORS, you will need to add the pekko-http-cors dependency to your project:
- sbt
libraryDependencies += "org.apache.pekko" %% "pekko-http-cors" % "1.0.0"
- Maven
<properties> <scala.binary.version>2.12</scala.binary.version> </properties> <dependencies> <dependency> <groupId>org.apache.pekko</groupId> <artifactId>pekko-http-cors_${scala.binary.version}</artifactId> <version>1.0.0</version> </dependency> </dependencies>
- Gradle
def versions = [ ScalaBinary: "2.12" ] dependencies { implementation "org.apache.pekko:pekko-http-cors_${versions.ScalaBinary}:1.0.0" }
And then serve the handlers with WebHandler.grpcWebHandler
WebHandler.grpcWebHandler
like this:
- Scala
-
source
import org.apache.pekko.grpc.scaladsl.WebHandler val grpcWebServiceHandlers = WebHandler.grpcWebHandler(greeterService, echoService) Http() .newServerAt("127.0.0.1", 8081) .bind(grpcWebServiceHandlers)
- Java
-
source
import org.apache.pekko.grpc.javadsl.WebHandler; Function<HttpRequest, CompletionStage<HttpResponse>> grpcWebServiceHandlers = WebHandler.grpcWebHandler(Arrays.asList(greeterService, echoService), sys, mat); Http.get(sys) .newServerAt("127.0.0.1", 8090) .bind(grpcWebServiceHandlers)