How to Call a ZIO HTTP API from Scala.js
In this guide, we call a ZIO HTTP API from a Scala.js program that runs in the browser. By the end, a page in the browser fetches a book from a ZIO HTTP server as a typed Book, first with the ZIO HTTP Client and then through an Endpoint that the server and the browser share.
We start with the sbt setup for a Scala.js client, write a small book API on the JVM, allow the browser's origin to call it, and send requests from the browser. The last section lists the parts of ZIO HTTP that do not work on Scala.js.
The Problem
A Scala.js program in the browser can call an HTTP API with the browser's Fetch API directly. It then works with JavaScript promises and untyped JSON, and turns the JSON into Scala values by hand.
For example, fetching a book with dom.fetch from scalajs-dom looks like this (Scala.js code, not compiled on this page):
import scala.concurrent.Future
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import org.scalajs.dom
final case class Book(id: Int, title: String, author: String)
object FetchBook {
def fetchBook(id: Int): Future[Book] =
dom.fetch(s"http://localhost:8080/books/$id").toFuture.flatMap { response =>
if (response.ok) response.json().toFuture
else Future.failed(new RuntimeException(s"Unexpected status ${response.status}"))
}.map { json =>
val book = json.asInstanceOf[js.Dynamic]
Book(
book.id.asInstanceOf[Int],
book.title.asInstanceOf[String],
book.author.asInstanceOf[String],
)
}
def main(args: Array[String]): Unit =
fetchBook(1).foreach(book => println(s"Fetched: $book"))
}
The URL, the status check, and every JSON field are written by hand. A typo in a field name or a field of the wrong type compiles, and the server and the client can drift apart without the compiler noticing. The result is a Future, so the call does not compose with the ZIO effects in the rest of the program.
ZIO HTTP is published for Scala.js, and its client runs in the browser on top of the Fetch API. The same Client, Request, Body, and Endpoint types work on both sides, so the browser can decode a response with the server's schema or call the server's endpoints directly.
Prerequisites
A Scala.js project needs the Scala.js sbt plugin. To share code between a JVM server and a Scala.js client, also add the cross-project plugin to project/plugins.sbt:
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.23.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.4.0")
Use sbt-scalajs 1.23.0 or later: ZIO HTTP is compiled with Scala.js 1.23.0, and an older linker rejects its classes with an IRVersionNotSupportedException.
Depend on ZIO HTTP with %%% instead of %%, so that each platform gets its own artifact. In this build.sbt, the api cross-project holds the code that both sides share, server runs on the JVM, and client is the Scala.js program:
val zioHttpVersion = "3.12.0"
lazy val api = crossProject(JSPlatform, JVMPlatform)
.crossType(CrossType.Pure)
.in(file("api"))
.settings(libraryDependencies += "dev.zio" %%% "zio-http" % zioHttpVersion)
lazy val server = project
.in(file("server"))
.dependsOn(api.jvm)
lazy val client = project
.in(file("client"))
.enablePlugins(ScalaJSPlugin)
.settings(scalaJSUseMainModuleInitializer := true)
.dependsOn(api.js)
scalaJSUseMainModuleInitializer := true makes the linked JavaScript file run the program's main method when the browser loads it. sbt client/fastLinkJS links the client to client/target/scala-2.13/client-fastopt/main.js (the Scala version in the path is your project's).
This guide assumes you know how to define routes and endpoints. If not, start with Routes and Endpoint.
The Shared Book API
Both sides use the same Book type and the same endpoint. This code goes in the shared api project:
import zio._
import zio.http._
import zio.http.endpoint.Endpoint
import zio.schema.{DeriveSchema, Schema}
final case class Book(id: Int, title: String, author: String)
object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}
object BookApi {
val getBook =
Endpoint(Method.GET / "books" / int("id"))
.out[Book]
.outError[String](Status.NotFound)
}
BookApi.getBook describes GET /books/{id}: it returns a Book as JSON, or a String with status 404 Not Found when there is no book with that id.
Allowing the Browser to Call the Server
The server implements the endpoint on the JVM. In this guide, the page that loads the Scala.js program is served from http://localhost:3000 and the API from http://localhost:8080. They are different origins, so the browser lets the page read the API's responses only when the API allows the page's origin with CORS (Cross-Origin Resource Sharing) headers. Middleware.cors adds those headers:
import zio.http.Header.{AccessControlAllowOrigin, Origin}
import zio.http.Middleware.{CorsConfig, cors}
val books = Map(
1 -> Book(1, "Programming in Scala", "Martin Odersky"),
2 -> Book(2, "Functional Programming in Scala", "Michael Pilquist"),
)
val corsConfig: CorsConfig =
CorsConfig(
allowedOrigin = {
case origin @ Origin.Value("http", "localhost", Some(3000)) =>
Some(AccessControlAllowOrigin.Specific(origin))
case _ => None
},
)
val api: Routes[Any, Response] =
Routes(
BookApi.getBook.implement { id =>
ZIO.fromOption(books.get(id)).orElseFail(s"No book with id $id")
},
) @@ cors(corsConfig)
allowedOrigin accepts only http://localhost:3000, and answers it with an Access-Control-Allow-Origin header that names that origin. A request with an Origin that it does not accept gets 403 Forbidden. Middleware.cors also adds the OPTIONS routes that answer the browser's preflight requests.
Without the CORS middleware, the server still answers, but the browser blocks the response and the client call fails. In Chromium, the call fails with scala.scalajs.js.JavaScriptException: TypeError: Failed to fetch, and the browser console shows that the request was blocked by CORS policy.
The runnable server serves the API on port 8080 and, on port 3000, a page whose only content is a <script> tag that loads main.js, the linked Scala.js program.
Runnable version, with the shared API from BookApi.scala: BookServer.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http::3.12.0"
// The types and the endpoint that BookServer (JVM) and the Scala.js clients share.
package example.scalajs
import zio.schema.{DeriveSchema, Schema}
import zio.http._
import zio.http.endpoint.Endpoint
final case class Book(id: Int, title: String, author: String)
object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}
object BookApi {
val getBook =
Endpoint(Method.GET / "books" / int("id"))
.out[Book]
.outError[String](Status.NotFound)
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http::3.12.0"
//> using file BookApi.scala
// Runs on the JVM. Serves the book API on port 8080 and the page that loads main.js on port 3000.
// Run from this folder: scala-cli run BookServer.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.scalajs.BookServer"
package example.scalajs
import java.io.File
import zio._
import zio.http.Header.{AccessControlAllowOrigin, Origin}
import zio.http.Middleware.{CorsConfig, cors}
import zio.http._
import zio.http.template._
object BookServer extends ZIOAppDefault {
private val books = Map(
1 -> Book(1, "Programming in Scala", "Martin Odersky"),
2 -> Book(2, "Functional Programming in Scala", "Michael Pilquist"),
)
val corsConfig: CorsConfig =
CorsConfig(
allowedOrigin = {
case origin @ Origin.Value("http", "localhost", Some(3000)) =>
Some(AccessControlAllowOrigin.Specific(origin))
case _ => None
},
)
val api: Routes[Any, Response] =
Routes(
BookApi.getBook.implement { id =>
ZIO.fromOption(books.get(id)).orElseFail(s"No book with id $id")
},
) @@ cors(corsConfig)
val page: Routes[Any, Response] =
Routes(
Method.GET / "" -> handler(Response.html(html(body(script(srcAttr := "/main.js"))))),
Method.GET / "main.js" -> Handler.fromFile(new File("main.js")).orDie,
)
val run =
Server.serve(api).provide(Server.defaultWithPort(8080)) <&>
Server.serve(page).provide(Server.defaultWithPort(3000))
}
Sending a Request from the Browser
On Scala.js, Client.default provides a client that sends requests with the browser's Fetch API. Requests, responses, and bodies are the same types as on the JVM, so the client decodes the response with the Book schema from the shared code:
import zio.schema.codec.JsonCodec.schemaBasedBinaryCodec
val fetchBook: ZIO[Client, Throwable, Unit] =
for {
response <- Client.batched(Request.get("http://localhost:8080/books/1"))
book <- response.body.to[Book]
_ <- Console.printLine(s"Fetched: $book")
} yield ()
Client.batched reads the whole response body before it returns the response. The import of schemaBasedBinaryCodec gives Body#to a JSON codec for every type with a Schema.
The Scala.js program is a ZIOAppDefault, as on the JVM:
object BrowserClient extends ZIOAppDefault {
val run = fetchBook.provide(Client.default)
}
In the browser, Console.printLine writes to the browser's developer console. Opening http://localhost:3000 prints:
Fetched: Book(1,Programming in Scala,Martin Odersky)
Client.streaming also works on Scala.js. It reads the response body as a stream from the Fetch API, and needs a Scope, as on the JVM.
Runnable version: BrowserClient.scala
//> using scala 2.13.18
//> using platform js
//> using jsVersion 1.23.0
//> using dep "dev.zio::zio-http::3.12.0"
//> using file BookApi.scala
// A Scala.js program for the browser. Link it to main.js from this folder:
// scala-cli --power package --js --js-cli-on-jvm BrowserClient.scala -o main.js -f
// then run BookServer and open http://localhost:3000 with the browser console open.
package example.scalajs
import zio._
import zio.schema.codec.JsonCodec.schemaBasedBinaryCodec
import zio.http._
object BrowserClient extends ZIOAppDefault {
val program: ZIO[Client, Throwable, Unit] =
for {
response <- Client.batched(Request.get("http://localhost:8080/books/1"))
book <- response.body.to[Book]
_ <- Console.printLine(s"Fetched: $book")
} yield ()
val run = program.provide(Client.default)
}
Calling the Shared Endpoint
Because BookApi.getBook is shared, the browser does not need to repeat its path, its JSON format, or its error status. An EndpointExecutor calls the endpoint through the browser's Client:
import zio.http.endpoint.EndpointExecutor
val callEndpoint: ZIO[Client & Scope, String, Unit] =
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
book <- executor(BookApi.getBook(1))
_ <- Console.printLine(s"Fetched: $book").orDie
missing <- executor(BookApi.getBook(42)).either
_ <- Console.printLine(s"Book 42: $missing").orDie
} yield ()
executor(BookApi.getBook(1)) builds the request from the endpoint, sends it, and decodes the response into a Book. The 404 Not Found for book 42 comes back as the String error that the endpoint declares, and either turns it into a Left. The calls run in a Scope:
object EndpointClient extends ZIOAppDefault {
val run = ZIO.scoped(callEndpoint).provide(Client.default)
}
It prints:
Fetched: Book(1,Programming in Scala,Martin Odersky)
Book 42: Left(No book with id 42)
When the page and the API have the same origin, Scala.js endpoints also have urlAbsolute, which builds the URL of a call from the protocol and host of window.location. For a page on http://localhost:3000, BookApi.getBook.urlAbsolute(1) returns Right(http://localhost:3000/books/1).
Runnable version: EndpointClient.scala
//> using scala 2.13.18
//> using platform js
//> using jsVersion 1.23.0
//> using dep "dev.zio::zio-http::3.12.0"
//> using file BookApi.scala
// A Scala.js program that calls BookApi.getBook through an EndpointExecutor. Link it to main.js from this folder:
// scala-cli --power package --js --js-cli-on-jvm EndpointClient.scala -o main.js -f
// then run BookServer and open http://localhost:3000 with the browser console open.
package example.scalajs
import zio._
import zio.http._
import zio.http.endpoint.EndpointExecutor
object EndpointClient extends ZIOAppDefault {
val program: ZIO[Client & Scope, String, Unit] =
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
book <- executor(BookApi.getBook(1))
_ <- Console.printLine(s"Fetched: $book").orDie
missing <- executor(BookApi.getBook(42)).either
_ <- Console.printLine(s"Book 42: $missing").orDie
} yield ()
val run = ZIO.scoped(program).provide(Client.default)
}
What Does Not Work on Scala.js
On Scala.js, ZIO HTTP is a client library. The client sends every request with the Fetch API, and the browser manages connections, TLS, and the request rules of the page. These parts of ZIO HTTP behave differently or are not available:
| Feature | On Scala.js |
|---|---|
Server (Server, Server.default, Server.serve) | Not available. A Scala.js program that refers to Server fails to link, because Server.Config uses java.net.InetSocketAddress, which Scala.js does not provide. |
WebSocket client (Client#socket) | Not available. The effect dies with an UnsupportedOperationException. |
ZClient.Config | Only addUserAgentHeader is used. SSL, proxy, connection pool, timeouts, decompression, and the other settings have no effect. |
Client#ssl and Client#proxy | No effect; the Fetch API does not take them. |
| Request methods | GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS work. TRACE, CONNECT, and custom methods make the request die with an IllegalArgumentException. |
| Request bodies | The whole request body is read into memory before the request is sent, including a streaming body. |
| Response bodies | Work in both modes: Client.batched reads the body before returning, and Client.streaming reads it as a stream. |
The browser also applies its own rules to every request: the CORS check from the section above, and headers that a page cannot set. For example, with addUserAgentHeader on, Chromium still sends its own User-Agent header instead of the client's.
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/scalajs/. From that folder:
-
Link a client to
main.js, for exampleBrowserClient:scala-cli --power package --js --js-cli-on-jvm BrowserClient.scala -o main.js -f--js-cli-on-jvmmakes Scala CLI download the Scala.js 1.23.0 linker that the file asks for with//> using jsVersion, instead of using its built-in linker, which can be older. -
Start the server in the same folder, so that it finds
main.js:scala-cli run BookServer.scala -
Open
http://localhost:3000and the browser's developer console.
To run EndpointClient instead, link it to main.js in step 1 and reload the page.
Going Further
- Client explains the batched and streaming modes and the rest of the client API.
- Endpoint shows how to describe inputs, outputs, and errors of an endpoint.
- From Routes to Declarative Endpoints builds an API from endpoints and calls it with an
EndpointExecutoron the JVM. - Middleware lists every field of
CorsConfig. - The Scala.js documentation covers the sbt plugin, linking, and calling JavaScript APIs.