gRPC-Web

Note

This feature is experimental.

The Java/Scala API’s to enable this feature may still change in further versions of Akka gRPC, and future versions of this feature may not work with services generated with older versions of Akka 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 Akka gRPC services.

However, in some situations it may be operationally simpler if your service supports gRPC-Web directly. This is now possible with Akka gRPC as well.

To serve a gRPC service with Akka 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.grpcWebHandlerWebHandler.grpcWebHandler to serve your gRPC-Web endpoint with basic CORS infrastructure in place. To use CORS, you will need to add the akka-http-cors dependency to your project:

sbt
libraryDependencies += "ch.megard" %% "akka-http-cors" % "0.4.2"
Maven
<dependency>
  <groupId>ch.megard</groupId>
  <artifactId>akka-http-cors_2.12</artifactId>
  <version>0.4.2</version>
</dependency>
Gradle
dependencies {
  compile group: 'ch.megard', name: 'akka-http-cors_2.12', version: '0.4.2'
}

And then serve the handlers with WebHandler.grpcWebHandlerWebHandler.grpcWebHandler like this:

Scala
import akka.grpc.scaladsl.WebHandler

val grpcWebServiceHandlers = WebHandler.grpcWebHandler(greeterService, echoService)

Http()
  .bindAndHandleAsync(
    grpcWebServiceHandlers,
    interface = "127.0.0.1",
    port = 8081,
    connectionContext = HttpConnectionContext())
Java
import akka.grpc.javadsl.WebHandler;

Function<HttpRequest, CompletionStage<HttpResponse>> grpcWebServiceHandlers =
    WebHandler.grpcWebHandler(Arrays.asList(greeterService, echoService), sys, mat);

Http.get(sys).bindAndHandleAsync(
    grpcWebServiceHandlers,
    ConnectHttp.toHost("127.0.0.1", 8091),
    mat)
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.