http4s-dom

Use http4s in your browser with Scala.js! Features:

Notably, http4s-dom can also be used to create serverless apps with Cloudflare Workers which have adopted the same APIs used in the browser!

Installation

http4s-dom Scala version support

// Supports http4s 0.23.x and scala-js-dom 2.x
libraryDependencies += "org.http4s" %%% "http4s-dom" % "0.2.0"

// Or, for compatibility with scala-js-dom 1.x
// libraryDependencies += "org.http4s" %%% "http4s-dom" % "0.1.0"

// recommended, brings in the latest client module
libraryDependencies += "org.http4s" %%% "http4s-client" % "0.23.6"

// optional, for JSON support
libraryDependencies += "org.http4s" %%% "http4s-circe" % "0.23.6"
libraryDependencies += "io.circe" %%% "circe-generic" % "0.15.0-M1"

Example

import cats.effect._
import cats.effect.unsafe.implicits._
import io.circe.generic.auto._
import org.http4s.circe.CirceEntityCodec._
import org.http4s.dom._
import org.scalajs.dom._

val client = FetchClientBuilder[IO].create

val activityElement = document.getElementById("activity")

case class Activity(activity: String)

val fetchActivity: IO[Unit] = for {
  _ <- IO(activityElement.innerHTML = "<i>fetching...</i>")
  activity <- client.expect[Activity]("https://www.boredapi.com/api/activity")
  _ <- IO(activityElement.innerHTML = activity.activity)
} yield ()

val button = document.getElementById("button").asInstanceOf[html.Button]

button.onclick = _ => fetchActivity.unsafeRunAndForget()

I'm bored.

Learn more

The FetchClientBuilder creates a standard http4s Client that is described in the http4s documentation. Similarly, the ServiceWorker FetchEvent listener integrates directly with http4s services.