Skip to content

REST Server ​

Uni provides HTTP servers on all three Scala platforms, all in the uni module: a built-in socket server on the JVM (JDK 24+) and Scala Native, and the Node.js http module on Scala.js. They share one configuration API and a type-safe, annotation-based router for building REST APIs. On the JVM, the optional uni-netty module runs the same code on Netty instead.

Which API is cross-platform?

Functional handlers (withHandler / withRxHandler), filters, the annotation router (@Endpoint, Router.of[T], RouterHandler), RPC, Server-Sent Events, and WebSocket routes work on every platform. Only backend tuning options differ — see Cross-Platform Servers.

Quick Start ​

Http.server runs with uni alone on every platform (on the JVM it needs JDK 24+):

scala
libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.3.12"
scala
import wvlet.uni.http.{HttpMethod, Request, Response}
import wvlet.uni.http.router.{Endpoint, Router}
import wvlet.uni.http.Http
import wvlet.uni.http.router.RouterHandler

// Define a controller
class UserController:
  @Endpoint(HttpMethod.GET, "/users")
  def listUsers(): String = """["alice", "bob"]"""

  @Endpoint(HttpMethod.GET, "/users/:id")
  def getUser(id: String): String = s"""{"id": "${id}"}"""

// Create router and start server
val router = Router.of[UserController]
val handler = RouterHandler(router)

Http
  .server
  .withPort(8080)
  .withRxHandler(handler)
  .start { server =>
    println(s"Server running on port ${server.localPort}")
    // Server runs until the block completes
  }

Cross-Platform Servers ​

Http.server starts the same server code on every platform. It picks the platform's backend, and each returns an HttpServer:

PlatformBackend for Http.serverBackend-only options
JVMNetty when uni-netty is on the classpath, otherwise the built-in server (JDK 24+)Netty.options (wvlet.uni.http.netty.Netty)
Scala.jsNode.js http— (all settings are shared)
Scala Nativenative socketsNative.options (wvlet.uni.http.Native)

A server that compiles and runs identically on every platform:

scala
import wvlet.uni.http.{Http, Response}
import wvlet.uni.rx.Rx

Http
  .server
  .withPort(8080)
  .withRxHandler { request =>
    Rx.single(Response.ok(s"Hello from ${request.path}"))
  }
  .start { server =>
    println(s"Listening on ${server.localAddress}")
  }

Http.server takes these builder methods on every platform:

scala
.withPort(8080)                       // 0 picks a random free port
.withHost("0.0.0.0")                  // default 127.0.0.1 (loopback only)
.withName("my-server")
.withHandler(f: Request => Response)        // sync handler
.withRxHandler(f: Request => Rx[Response])  // async handler
.withFilter(filter)                         // RxHttpFilter
.start { server => ... }                    // block form, auto-stops
.start()                                    // returns the HttpServer

On the JVM, uni-netty registers Netty as the backend through java.util.ServiceLoader. Without it, Http.server starts Uni's built-in server, which needs JDK 24+ and no other dependency. The built-in server runs the same HTTP/1.1 and WebSocket code as the Scala Native server, with one virtual thread per connection. Like Netty, it limits the request line and headers, decodes chunked and gzip/deflate request bodies, answers Expect: 100-continue, and compresses responses for Accept-Encoding. As on Netty, a handler has no time limit, and stop() waits up to 30 s for in-flight requests to finish (closing idle connections, SSE streams, and WebSockets at once). Its limits and timeouts are the shared Http.server settings below, so it takes no options of its own; add uni-netty when you want Netty's own options (native transport, handler executor threads, ...) or an older JDK:

scala
// Optional: serve Http.server on Netty (JVM only; pulls in uni transitively)
libraryDependencies += "org.wvlet.uni" %% "uni-netty" % "2026.3.12"

Handlers, routers, and filters do not change when you add or remove it. examples/rpc-native serves a typed RPC API this way, with one Main for the JVM and Scala Native.

Tuning one backend ​

Http.server also takes the limits and timeouts the backends share, so they carry over when an app adds or drops uni-netty or builds for another platform. Settings you leave unset keep the backend's own default, and each backend applies the ones it supports:

SettingDefaultIgnored by
withMaxContentLength(bytes)1 MiB (Netty: 64 KiB)—
withMaxInitialLineLength(bytes)4 KiBNode.js (its maxHeaderSize covers the request line)
withMaxHeaderSize(bytes)8 KiB (Node.js: 16 KiB)—
withRequestReadTimeoutMillis(ms) / noRequestReadTimeout30 s (Node.js: 300 s)—
withIdleTimeoutMillis(ms)30 s (Node.js: 5 s; Netty: the request read timeout covers it)—
withWriteTimeoutMillis(ms) / noWriteTimeout30 s (Netty: off)Node.js
withRequestDecompression / noRequestDecompressiononNode.js (never decodes)
withMaxDecompressedRequestSize(bytes)64 MiBNode.js
withMaxStreamingConnections(n)256 (Native: worker threads minus up to 4)Node.js
withShutdownTimeoutMillis(ms)30 sNode.js
withWebSocketMaxFrameSize(bytes), withWebSocketPingIntervalMillis(ms)1 MiB, off—

The built-in JVM server, Scala Native, and Netty count the request read timeout from the request's first bytes once an idle timeout is set; the wait before them is the idle timeout. Netty times each write as a whole rather than per 64 KiB piece, and counts only Server-Sent Events streams toward maxStreamingConnections (the socket servers also count WebSockets).

For an option only one backend has (Netty transport and handler executor, Native worker threads, ...), pass that backend's options to withBackend: Netty.options (wvlet.uni.http.netty.Netty) on the JVM, or Native.options on Scala Native. They hold only that backend's own settings, so port, handler, limits, and timeouts are set in one place, on Http.server. Each backend applies only its own options, so options for several platforms can be passed together. (Node.js has no options of its own.)

Keep the server code shared and bind the options per platform with Design:

scala
// shared
import wvlet.uni.design.Design
import wvlet.uni.http.{Http, HttpServer, Response, ServerOptions}

val serverDesign = Design
  .newDesign
  .bindProvider[ServerOptions, HttpServer] { options =>
    Http.server.withPort(8080).withHandler(_ => Response.ok("ok")).withBackend(options).start()
  }
  .onShutdown(_.stop())

// .jvm/src/main/scala
import wvlet.uni.http.netty.Netty
val platformDesign = Design
  .newDesign
  .bindInstance[ServerOptions](Netty.options.withHandlerExecutorThreads(8).withShutdownHook)

// .native/src/main/scala
import wvlet.uni.http.Native
val platformDesign = Design
  .newDesign
  .bindInstance[ServerOptions](Native.options.withWorkerThreads(32))

JVM-only apps: Netty.server ​

When a project only runs on the JVM, Netty.server (wvlet.uni.http.netty.Netty) builds the Netty server directly. Every setting, shared or Netty-only, is a method of the one config, start() returns a NettyHttpServer, and a missing uni-netty dependency fails at compile time instead of at start():

scala
import wvlet.uni.http.Response
import wvlet.uni.http.netty.Netty

Netty
  .server
  .withPort(8080)
  .withHandlerExecutorThreads(8)
  .withGracefulShutdown(quietPeriodSeconds = 2, timeoutSeconds = 15)
  .withHandler(_ => Response.ok("ok"))
  .start { server =>
    println(s"Listening on ${server.localAddress}")
  }

Pick Http.server when the same server code should also build for Scala.js or Scala Native, and Netty.server when it never will. Switching later only changes where the Netty-only settings go: into withBackend(Netty.options...).

Routing without annotations

The annotation router works on every platform. For a few routes, you can also match on the path inside a functional handler:

scala
import wvlet.uni.http.Http

Http
  .server
  .withPort(8080)
  .withRxHandler { request =>
    request.path match
      case "/health"      => Rx.single(Response.ok("ok"))
      case s"/users/${id}" => Rx.single(Response.ok(s"user ${id}"))
      case _              => Rx.single(Response.notFound)
  }
  .start()

Garbage collector on Scala Native

Use Scala Native 0.5.13 or later with its default collector, Immix. Earlier versions of Immix could free or overwrite live objects when several threads allocated at once (scala-native#5046, #5160), and the server runs handlers on worker threads. On 0.5.12, build with nativeConfig ~= (_.withGC(scala.scalanative.build.GC.boehm)) instead.

Cap the heap. Immix grows its heap well past a server's live data: in the rpc-native benchmark on 18 cores, RSS reached 266 MB, and with a 64 MB cap it stayed at 74 MB at the same or better throughput. Set the cap at build time with .withGarbageCollectorConfig(_.withMaxHeapSize(...)), or at run time with GC_MAXIMUM_HEAP_SIZE.

Immix beat Boehm in that benchmark (24k vs 15k req/s on x86_64, 26k vs 22k on arm64, at a lower p99), since Boehm serves larger objects under one global lock. For apps that still choose Boehm, Uni runs it with one marker thread (set GC_MARKERS to override) and starts a Native server with a 16 MB Boehm heap (set GC_INITIAL_HEAP_SIZE to choose another size).

The rest of this page uses Http.server with the annotation router. The router, the request/response model, response conversion, and filters described below work on every platform.

Defining Endpoints ​

Use the @Endpoint annotation to mark controller methods as HTTP endpoints:

scala
import wvlet.uni.http.HttpMethod
import wvlet.uni.http.router.Endpoint

class ApiController:
  @Endpoint(HttpMethod.GET, "/health")
  def health(): String = "ok"

  @Endpoint(HttpMethod.POST, "/data")
  def createData(request: Request): Response =
    val body = request.content.toContentString
    Response.ok(s"Received: ${body}")

  @Endpoint(HttpMethod.PUT, "/items/:id")
  def updateItem(id: String, request: Request): Response =
    Response.ok(s"Updated item ${id}")

  @Endpoint(HttpMethod.DELETE, "/items/:id")
  def deleteItem(id: String): Response =
    Response.noContent

Only wvlet.uni.http.router.Endpoint defines a route. An annotation from another framework with the same simple name (e.g., one kept on an API trait for documentation generation) is ignored, and a Uni @Endpoint whose method or path cannot be read fails when the router is built.

Path Parameters ​

Use :paramName syntax in the path to capture path segments:

scala
class ItemController:
  @Endpoint(HttpMethod.GET, "/items/:id")
  def getItem(id: String): String = s"Item ${id}"

  @Endpoint(HttpMethod.GET, "/users/:userId/posts/:postId")
  def getUserPost(userId: String, postId: String): String =
    s"User ${userId}, Post ${postId}"

Path parameter names must match the method parameter names.

Query Parameters ​

Method parameters that don't match path parameters are automatically bound from query string:

scala
class SearchController:
  @Endpoint(HttpMethod.GET, "/search")
  def search(query: String, limit: Int = 10): String =
    s"Searching for '${query}' with limit ${limit}"

Request: GET /search?query=hello&limit=20

Supported parameter types:

  • String
  • Int, Long, Short, Byte
  • Double, Float
  • Boolean
  • Option[T] for optional parameters

Request Object Access ​

Add a Request parameter to access the full request:

scala
class MyController:
  @Endpoint(HttpMethod.POST, "/upload")
  def upload(request: Request): Response =
    val contentType = request.headers.get("Content-Type")
    val body = request.content.toContentString
    Response.ok(s"Received ${body.length} bytes")

Request Body ​

Parameters not bound from the path or query string are read from the request body, decoded with a Weaver:

scala
case class Message(role: String, text: String)
case class MessagesRequest(model: String, messages: Seq[Message])

class ChatController:
  // The whole JSON body decodes into `request`; `httpRequest` is the raw Request
  @Endpoint(HttpMethod.POST, "/v1/messages")
  def messages(request: MessagesRequest, httpRequest: Request): Reply = ???

  // Several body parameters: each is read from the JSON object field of its name
  @Endpoint(HttpMethod.POST, "/projects/:id/rename")
  def rename(id: String, name: String, tags: Seq[String]): Project = ???
  • When exactly one parameter, other than Request, RequestAttributes, and path parameters, is not a primitive, the whole body decodes into it, and the other parameters come from the query string. A collection or map parameter takes the whole body only when it is the only such parameter. Otherwise the body must be an object, and each parameter is read from the field of the same name. Unknown fields are ignored.
  • Content types: JSON (application/json, *+json, or no Content-Type), and MessagePack (application/msgpack or application/x-msgpack).
  • Custom codecs: a given Weaver[A] in A's companion object, or imported where Router.of is called, is used when the parameter type is A, or a case class with an A field. Weavers are resolved when Router.of is compiled, so a given that is only in scope elsewhere is not seen. For Option[A], Seq[A], or a sealed trait, define a given for that type to get the same.
  • Errors return 400 and never echo the body: malformed JSON or MessagePack, a value of the wrong shape, or a missing body for a non-Option object parameter. A required body in another content type (e.g. a form post) returns 415.
  • A method that also takes Request may read the body itself: a body that does not fit its other parameters is an error only when a required parameter is left without a value. A body without a Content-Type that does not parse is always left alone.

Streaming Request Bodies ​

A request body is read into memory before the handler runs, up to withMaxContentLength. For large uploads, mark the requests whose body the handler reads as a stream instead:

scala
import wvlet.uni.http.{Http, HttpContent, HttpMethod, Request, Response}

import java.nio.file.{Files, Paths, StandardCopyOption}

Http
  .server
  .withPort(8080)
  .withStreamingRequests(req => req.method == HttpMethod.PUT && req.path.startsWith("/files/"))
  .withHandler { (req: Request) =>
    req.content match
      case body: HttpContent.StreamContent =>
        val target = Paths.get("/data", req.path.stripPrefix("/files/"))
        Files.copy(body.openStream, target, StandardCopyOption.REPLACE_EXISTING)
        Response.ok
      case _ =>
        Response.notFound
  }
  .start()
  • The predicate sees the request head (method, path, headers) before any body bytes are read. Other requests are buffered as before.
  • Filters run before the body is read. A client that sends Expect: 100-continue gets 100 Continue only when the handler first reads, so a filter that rejects the request (for example, a failed auth check) stops it before anything is uploaded.
  • length is the Content-Length, or -1 for a chunked body.
  • The stream can be read from any thread until the response is sent; later reads throw IOException.
  • toContentBytes reads what is left and keeps it, so a filter that reads the body (such as RPC argument logging) leaves it for the handler.
  • A body that breaks off makes reads throw HttpContent.RequestBodyException, and the server answers with its status instead of the handler's response:
    • malformed chunks: 400
    • no complete body within withStreamingRequestTimeoutMillis (default 1 hour from the end of the head), or no bytes for 30 s: 408
    • more than withMaxStreamingRequestSize (default 1 GiB): 413
  • When the handler returns without reading everything, the server reads and discards up to 64 KiB of the rest so the connection can be reused, and otherwise closes the connection.
  • Streamed bodies are not decompressed: the handler sees Content-Encoding and the bytes as sent.
  • Each upload takes a withMaxStreamingConnections slot while its handler runs (503 when none is free), so on Scala Native uploads can't occupy every worker. Streaming requests have no handler timeout; the deadlines above bound them.

The built-in JVM server and Scala Native read the body from the socket as the handler reads it. Netty and Node.js still buffer it within withMaxContentLength, then hand the handler a StreamContent over the buffered bytes, so the same handler code works on every backend. Netty sends 100 Continue before filters run.

Request and Response ​

Request Properties ​

scala
request.method              // HttpMethod (GET, POST, etc.)
request.uri                 // Full URI string
request.path                // Path portion of URI
request.headers             // HttpHeaders
request.content             // HttpContent (request body)
request.getQueryParam(name) // Option[String]

Response Factory Methods ​

scala
Response.ok                        // 200 OK
Response.ok("body")                // 200 with text body
Response.created                   // 201 Created
Response.noContent                 // 204 No Content
Response.badRequest("message")     // 400 Bad Request
Response.notFound                  // 404 Not Found
Response.notFound("message")       // 404 with message
Response.internalServerError(msg)  // 500 Internal Server Error

Response Content ​

scala
Response.ok
  .withTextContent("Hello")           // text/plain
  .withJsonContent("""{"a": 1}""")    // application/json
  .withBytesContent(bytes)            // application/octet-stream
  .withContent(HttpContent.json(str)) // Custom content
  .addHeader("X-Custom", "value")     // Add header

Response Conversion ​

Controller methods can return various types that are automatically converted to responses:

Return TypeConversion
ResponseReturned as-is
Rx[Response]Async response
String200 OK with text/plain
Seq[T]200 OK with JSON array
Map[K, V]200 OK with JSON object
Option[T]Value or 204 No Content
Unit204 No Content
Other typesSerialized to JSON
scala
class DataController:
  @Endpoint(HttpMethod.GET, "/text")
  def getText(): String = "plain text"

  @Endpoint(HttpMethod.GET, "/list")
  def getList(): Seq[String] = Seq("a", "b", "c")

  @Endpoint(HttpMethod.GET, "/map")
  def getMap(): Map[String, Int] = Map("count" -> 42)

  @Endpoint(HttpMethod.GET, "/async")
  def getAsync(): Rx[Response] =
    Rx.single(Response.ok("async result"))

Filters ​

Use RxHttpFilter to intercept requests and responses:

scala
import wvlet.uni.http.{RxHttpFilter, RxHttpHandler}

val loggingFilter = RxHttpFilter { (request, next) =>
  println(s"Request: ${request.method} ${request.path}")
  next
    .handle(request)
    .map { response =>
      println(s"Response: ${response.status}")
      response
    }
}

val authFilter = RxHttpFilter { (request, next) =>
  request.headers.get("Authorization") match
    case Some(token) if isValid(token) =>
      next.handle(request.addHeader("X-User-Id", extractUserId(token)))
    case _ =>
      Rx.single(Response.unauthorized.withTextContent("Missing or invalid token"))
}

Handling Errors in a Filter ​

An exception thrown by a controller method reaches the enclosing filters as a failed Rx, the same as an exception inside a returned Rx. A filter can recover from it and map the original exception to a response, so error classification can live in one place:

scala
val errorFilter = RxHttpFilter { (request, next) =>
  next
    .handle(request)
    .recover {
      case e: IllegalArgumentException => Response.badRequest(e.getMessage)
    }
}

An exception that no filter recovers from becomes a generic 500 Internal Server Error (see Security Defaults), except a ServiceException: throw ServiceStatus.NOT_FOUND_U5.newException("no such user") (from wvlet.uni.http) and the server answers with that status's HTTP status (404 here), the X-RPC-Status header, and the same JSON error body RPC endpoints send, which ServiceException.fromResponse reads back. With .withDetailedErrors(true) the body also carries its stack trace, except for UNAUTHENTICATED_U13 and PERMISSION_DENIED_U14 or an exception built with noStackTrace. A browser client on another origin can read X-RPC-Status only when the CORS policy exposes it: CorsPolicy().withExposedHeaders("X-RPC-Status"). A 4xx ServiceException is logged at debug level, since it reports a client error. Because a failed Rx skips map, a filter that decorates every response (logging, headers) never sees this error response. Place such a filter outside an error filter that recovers, or handle the failure itself with recover/tapOnFailure. A malformed path or query parameter is answered with 400 by RouterHandler itself, before any exception reaches a filter.

Applying Filters ​

scala
// Apply filter to server
Http
  .server
  .withPort(8080)
  .withFilter(loggingFilter)
  .withFilter(authFilter)
  .withRxHandler(handler)
  .start()

// Or compose filters
val combinedFilter = loggingFilter.andThen(authFilter)

Router-Level Filters ​

Define filters that apply to specific controllers:

scala
class LogFilter extends RxHttpFilter:
  def apply(request: Request, next: RxHttpHandler): Rx[Response] =
    println(s"Handling: ${request.path}")
    next.handle(request)

val router = Router
  .filter[LogFilter]
  .andThen(Router.of[UserController])

Passing Data from a Filter to Controllers ​

A filter can attach server-side attributes to the request, e.g. the identity an authentication filter resolved. Attributes never come from the client: a request decoded by the server starts with none, so a client cannot spoof them with headers. Since Request is immutable, each attribute stays with the request it was set on.

scala
import wvlet.uni.http.{Request, RequestAttribute, RequestAttributes, RxHttpFilter}

object Auth:
  // Keys compare by identity: share this instance rather than re-creating it by name
  val Identity: RequestAttribute[User] = RequestAttribute("identity")

  val filter = RxHttpFilter { (request, next) =>
    authenticate(request) match
      case Some(user) => next.handle(request.withAttribute(Identity, user))
      case None       => Rx.single(Response.unauthorized)
  }

class ApiController:
  @Endpoint(HttpMethod.GET, "/me")
  def me(request: Request): User = request.attribute(Auth.Identity).get

  // Or take the attributes alone
  @Endpoint(HttpMethod.GET, "/me/name")
  def name(attributes: RequestAttributes): String = attributes.get(Auth.Identity).get.name

The Netty server sets RequestAttribute.RemoteAddress (host:port of the connected peer, with IPv6 hosts in brackets, which is the load balancer when there is one). RequestAttributes.toString prints only the attribute names, so logging a request does not leak their values.

Access Log ​

HttpAccessLogFilter writes one entry per request, using the field names of Airframe's HttpLogger (method, path, status_code, response_time_ms, request_size, response_size, remote_address, request_header, response_header, exception_class, ...):

scala
import wvlet.uni.http.{HttpAccessLogConfig, HttpAccessLogFilter, HttpAccessLogWriter}
import wvlet.uni.log.FileLogHandlerConfig

val accessLog = HttpAccessLogFilter(
  HttpAccessLogWriter.jsonFile(FileLogHandlerConfig("log/http_server.json")),
  HttpAccessLogConfig()
    .withStreamWriter(HttpAccessLogWriter.jsonFile(FileLogHandlerConfig("log/http_stream.json")))
)

Http
  .server
  .withFilter(accessLog.andThen(authFilter)) // outermost, so it sees the final response
  .withRxHandler(RouterHandler(router))
  .start()

// In an inner filter or a controller
HttpAccessLogFilter.addEntry(request, "user_id", user.id)
  • authorization, proxy-authorization, cookie, set-cookie, and x-api-key are logged as [redacted]. withRedactedHeaders(...) replaces the list, and withExcludedHeaders(...) leaves headers out.
  • A request that reaches an @Endpoint or RPC method also gets rpc_interface, rpc_class, rpc_method, and rpc_args, the decoded method arguments. These fields are recorded even when the method throws.
  • Parameters and fields marked @secret (wvlet.uni.surface.secret) are left out of rpc_args, at any depth inside case classes, Seq, Option, Map, and arrays. A value whose fields can't be inspected, such as an argument typed as a sealed trait, is logged as its class name, never as its toString. Request arguments are skipped. noRpcArgs() turns rpc_args off.
  • A controller exception is logged with status 500 and its class and message, and is then rendered by the server as usual.
  • An SSE response gets a second entry when the stream ends (stream_event_count, stream_bytes, stream_duration_ms), written to the stream writer.
  • jsonFile writes JSON lines with daily and size-based rotation. For Fluentd or another sink, implement HttpAccessLogWriter.write(entry: Map[String, Any]).
  • Requests rejected before filters run (oversized or malformed bodies, read timeouts, the host check) are not logged.

CORS ​

CorsFilter lets a page on another origin call the server. It answers CORS preflights (OPTIONS with Access-Control-Request-Method) itself, and adds Access-Control-Allow-Origin to responses for allowed origins. The default CorsPolicy allows no origin:

scala
import wvlet.uni.http.{CorsFilter, CorsPolicy, HttpMethod}

val cors = CorsFilter(
  CorsPolicy()
    .withAllowedOrigins("https://app.example.com", "http://localhost:5173")
    .withAllowedMethods(HttpMethod.GET, HttpMethod.POST)
    .withAllowCredentials(true)
)

Http
  .server
  .withFilter(accessLog) // outermost
  .withFilter(cors)      // a server filter, so it also answers preflights for unrouted paths
  .withRxHandler(RouterHandler(router))
  .start()
  • An allowed preflight gets 204 with Access-Control-Allow-Methods, -Headers, -Max-Age (600 s by default), and -Credentials when enabled. A preflight from a disallowed origin, or for a method or header the policy doesn't allow, gets 403.
  • Requests from a disallowed origin are still handled, but get no CORS headers, so the browser keeps the page from reading the response. CORS protects what a page can read; it does not authenticate requests.
  • Responses get Vary: Origin (kept alongside the handler's own Vary values), so a cache does not serve one origin's answer to another. With withAllowedOrigins("*") the answer is the same for every origin, and Vary is left alone.
  • withAllowedOrigins matches exactly, ignoring case and a trailing slash. For patterns, use withOriginFilter(o => pattern.matches(o)), and anchor the pattern at the end so app.example.com.evil.test does not match.
  • withAllowedOrigins("*") answers Access-Control-Allow-Origin: *. It cannot be combined with withAllowCredentials(true): CorsFilter throws IllegalArgumentException.
  • By default a preflight may ask for any request header. withAllowedHeaders(...) limits them, and withExposedHeaders(...) lets the page read more response headers.
  • A handler failure on a request from an allowed origin becomes a generic 500 inside CorsFilter, with the CORS headers, so the browser sees the 500 rather than a CORS error. The exception is logged, and the access log records its exception_class and exception_message. The body is always Internal Server Error, even with withDetailedErrors; a ServiceException keeps its mapped status and error body, without a stack trace unless the exception asks for one. Failures on other requests reach the server unchanged. Add an error filter that maps exceptions to statuses after CorsFilter (inside it): placed outside, it never sees an allowed origin's failure, which CorsFilter has already turned into a 500.
  • WebSocket upgrades are not affected; they use withAllowedOrigins on the server.

Server Configuration ​

Server Options ​

scala
import wvlet.uni.http.Http
import wvlet.uni.http.netty.Netty

Http
  .server
  .withPort(8080)                      // Port to listen on (0 for random)
  .withHost("0.0.0.0")                 // Bind address (default: 127.0.0.1)
  .withName("my-server")               // Server name for logging
  .withMaxContentLength(1024 * 1024)   // Max request body size (Netty default: 64KB)
  .withMaxHeaderSize(8192)             // Max header size
  .withMaxInitialLineLength(4096)      // Max request line length
  .withRequestReadTimeoutMillis(30000) // Close connections that stall before a full request
  .withIdleTimeoutMillis(60000)        // Close keep-alive connections idle this long
  .withMaxDecompressedRequestSize(64 * 1024 * 1024) // Max decoded size of a gzip/deflate body
  .withBackend(Netty.options.noNativeTransport) // Netty-only: disable epoll/kqueue
  .withHandler(handler)
  .start()

Netty-only options go in Netty.options and Native-only ones in Native.options; see Tuning one backend.

Request Decompression ​

The Netty, built-in JVM, and Scala Native servers decode request bodies sent with Content-Encoding: gzip or deflate (and the x-gzip / x-deflate aliases) before any filter or handler sees them, and removes the Content-Encoding header. Other encodings such as br pass through unchanged.

  • A compressed body that decodes to more than withMaxDecompressedRequestSize bytes (default 64 MiB) gets a plain-text 413, and the connection is closed. Uncompressed requests are not counted against this limit.
  • A malformed compressed body gets a plain-text 400, and the connection is closed.
  • The decoded body must also fit in withMaxContentLength, so raise both for large compressed uploads.
  • .noRequestDecompression passes the compressed bytes to the handler, e.g. to authenticate a request before inflating it.
  • On Scala Native, the server links zlib (libz), which almost every system and base image provides.

Security Defaults ​

All three backends start with these defaults:

DefaultWhyOpt out
Bind to 127.0.0.1An unauthenticated dev or sidecar server is not reachable from the network.withHost("0.0.0.0") for Docker, Kubernetes, or any server other hosts must reach
500 responses say only Internal Server Error; RPC errors say Internal error; a thrown ServiceException sends its message but no stack traceException messages can leak file paths, SQL, hostnames, or credentials. The full exception is logged on the server.withDetailedErrors(true) on the server config, which also covers RouterHandler controller exceptions; RPCHandler(router).withDetailedErrors(true) for RPC
On a loopback server, requests whose Host is not localhost, *.localhost, 127.0.0.1 or [::1] get 403DNS rebinding: a web page can point its own host name at 127.0.0.1 and then read the local server as same-origin. The browser still sends the page's host name in Host.withAllowedHosts("app.example.com", "*.internal.example") to replace the list, .noHostCheck to accept any. A server bound to 0.0.0.0 accepts any host unless withAllowedHosts is set
WebSocket upgrades from another browser origin get 403Browsers attach cookies to cross-origin WebSocket handshakes (cross-site WebSocket hijacking).withAllowedOrigins("https://app.example.com"), or "*" for any origin
Bounded request sizeA single huge request cannot exhaust memory.withMaxContentLength for the body (defaults: Netty 64 KB, Node 1 MB, built-in and Native 1 MB; 413 for larger bodies). The request line (4 KB, else 414) and headers (8 KB, else 431) have their own limits: .withMaxInitialLineLength / .withMaxHeaderSize. withMaxDecompressedRequestSize for gzip/deflate bodies (default 64 MiB)
Request read timeout (30 s)Bounds slowloris clients that trickle a request.withRequestReadTimeoutMillis(...) / .noRequestReadTimeout. The built-in and Native servers measure from the request's first bytes (408 when it expires); idle keep-alive connections close after .withIdleTimeoutMillis(...)
Response write timeout (built-in and Native: 30 s)A client that stops reading a response cannot hold a thread.withWriteTimeoutMillis(...) / .noWriteTimeout (off by default on Netty)
Strict request parsingA front proxy and the server cannot disagree on where a request ends (request smuggling)— A bare CR or LF, obs-fold, whitespace before a header colon, a header name that is not a token, control characters in a value, a non-numeric or repeated Content-Length, more than one Host, and a Transfer-Encoding other than chunked get 400 or 501. A request with both Transfer-Encoding and Content-Length is read as chunked and closes the connection
Bounded long-lived connectionsIdle Server-Sent Events streams (and WebSockets on Native) cannot exhaust threads or starve ordinary requests; over the limit they get 503.withMaxStreamingConnections(n). Netty and built-in default: 256 (SSE streams only on Netty). Native default: workerThreads minus up to 4 workers kept for ordinary requests
CR, LF, or NUL in a header name or value is rejectedPrevents HTTP response splitting when a header echoes user input— (addHeader/setHeader throw IllegalArgumentException)

Requests without an Origin header (CLI tools, server-to-server clients) and same-origin pages are always accepted for WebSocket. A malformed path or query parameter (e.g. ?limit=abc for an Int) returns 400 rather than 500.

On Scala Native, the workerThreads workers bound how many requests run at once. By default there is one worker per core, at least 4 and at most 16 (16 on Windows). Workers beyond the core count add latency, not throughput: on a 2-core server (Immix, 16 connections), 2, 4, and 16 workers served about the same requests per second at a p99 of 0.7, 3.1, and 12.3 ms. So on a host with fewer than 4 cores and non-blocking handlers, Native.options.withWorkerThreads(cores) gives the lowest latency. On Linux and macOS, a keep-alive connection waiting for its next request holds no worker: it waits in an epoll/kqueue poller, so the number of open connections is limited only by the process's file descriptor limit. A request still being received does hold its worker, and the timeouts above bound how long a slow client keeps one. So raise Native.options.withWorkerThreads(n) for handlers that block, or for many slow clients, or put a reverse proxy in front. On Windows, each connection holds a worker while it is open. The built-in JVM server runs each connection on a virtual thread and has no such limit.

TLS is not built in: terminate HTTPS at a reverse proxy or load balancer.

Tuning a Public API Server ​

The defaults suit a small internal service. A public API server usually reviews these together:

SettingDefaultWhen to change
.withMaxContentLength(n)1 MB (Netty: 64 KB)Raise it to the largest request body the API accepts, e.g. LLM prompts with images. A decompressed body must also fit in this limit
.withIdleTimeoutMillis(ms)30 sKeep it longer than the idle timeout of the load balancer in front of the server, or the server closes connections the balancer still reuses. On Netty without it, the request read timeout closes idle connections
.withMaxStreamingConnections(n)256The maximum number of concurrent SSE streams per server; streams beyond it get 503. Size it to the expected number of concurrent streaming clients
.withHost("0.0.0.0") / .withAllowedHosts(...)127.0.0.1, loopback host checkRequired behind a load balancer or in a container
.withDetailedErrors(true)offKeep it off in production; the full exception is logged on the server

Server Lifecycle ​

scala
// Start and get server instance
val server = Http
  .server
  .withPort(8080)
  .withHandler(handler)
  .start()

println(s"Running on port ${server.localPort}")
server.isRunning  // true

// Stop when done
server.stop()
server.isRunning  // false

Block-based Server ​

For simpler use cases, use the block form that automatically stops the server:

scala
Http
  .server
  .withPort(8080)
  .withHandler(handler)
  .start { server =>
    // Server runs while this block executes
    println(s"Server on port ${server.localPort}")
    Thread.sleep(60000)  // Run for 1 minute
  }
// Server automatically stopped here

Simple Handler ​

For simple cases without routing, use a direct handler:

scala
Http
  .server
  .withPort(8080)
  .withHandler { request =>
    Response.ok(s"Hello from ${request.path}")
  }
  .start()

Or with async responses:

scala
Http
  .server
  .withPort(8080)
  .withRxHandler { request =>
    Rx.single(Response.ok("async response"))
  }
  .start()

Static Files ​

StaticFiles serves files from a directory, such as a built web frontend, next to your API on the same server. It is a filter: a GET for a file under the root returns the file, and every other request goes on to your handler.

scala
import wvlet.uni.http.{Http, StaticFiles}

Http
  .server
  .withPort(8080)
  .withFilter(StaticFiles("dist").withSpaFallback(true))
  .withRxHandler(api)
  .start()
RequestResponse
GET /assets/app.jsThe file, as text/javascript; charset=utf-8
GET / or GET /docs/The directory's index.html (withIndexFile changes the name)
POST /assets/app.js, GET /api/usersYour handler
GET /chats/42 from a browser, unknown to your handlerindex.html, with withSpaFallback(true)

It works on the JVM, Node.js, and Scala Native. A relative root resolves against the current directory, and the root may be created after the server starts.

Safe defaults ​

A request that could reach outside the root, or reach a file you did not mean to publish, gets a plain 404. The response doesn't say why, so it reveals nothing about the file system.

  • Path traversal: each path segment is percent-decoded once, and a segment of . or .., an empty one, or one containing /, \, :, NUL, or another control character is refused. So are names that Windows rejects or aliases (<>"|?*, a trailing dot or space, 8.3 short names like GIT~1), on every platform.
  • Symbolic links: every component below the root is checked without following links, and a link (or NTFS junction) anywhere below the root is refused, even one that points inside it. The root itself may be a link.
  • Dotfiles: names starting with . (.env, .git/) are refused, except .well-known/. withDotfiles(true) serves them.
  • Directories: only the index file is served; there are no listings. A directory path needs its trailing slash (/docs/), so relative links in its index resolve correctly.
  • Content types: a built-in table covers the usual web build output (HTML, CSS, JavaScript, JSON, source maps, SVG, images, fonts, WebAssembly). Other extensions are served as application/octet-stream, and every response sets X-Content-Type-Options: nosniff so a browser never guesses a type. Add a type with withContentType("glb", ContentType("model/gltf-binary")).
  • Caching: every file gets an ETag from its size and modification time, and Cache-Control: no-cache, so the browser revalidates on each load. A request whose If-None-Match matches gets 304 Not Modified without the file being read, and a new build is picked up on the next load. Set another policy with withCacheControl("max-age=3600"), or send none with noCacheControl.
  • Range requests: every file response sends Accept-Ranges: bytes. A single range (Range: bytes=0-1023, bytes=1024-, or bytes=-512) gets 206 Partial Content, so a <video> can seek and a download can resume. A range that starts past the end gets 416. Requests for several ranges get the whole file. With If-Range, the range is served only while the client's ETag still matches.
  • Streaming: files are sent from disk in bounded chunks, never read whole into memory, on every backend.

Filters run in the order you add them. Add StaticFiles after an authentication filter to protect the files, or before it to keep them public.

Serving a file from a handler

A handler can stream a file, or part of one, too: Response.ok(HttpContent.FileContent(path, offset, length, Some(contentType))). The server reads it in chunks as it sends, and code that needs the bytes (contentAsBytes) reads the range on demand.

WebSocket ​

Every server backend (Netty, the built-in JVM server, Scala Native, and Node.js) supports WebSocket connections. WebSocket routes are registered by path, separately from the REST router, because connections are stateful and bidirectional rather than request/response. A fresh WebSocketHandler is created per connection, so it may hold per-connection state; all of its callbacks have no-op defaults, so you override only what you need.

scala
import wvlet.uni.http.{WebSocketContext, WebSocketHandler}
import wvlet.uni.http.Http

Http
  .server
  .withPort(8080)
  .withWebSocketRoute("/ws/echo") { request =>
    new WebSocketHandler:
      override def onOpen(ctx: WebSocketContext): Unit =
        ctx.send("welcome")
      override def onTextMessage(ctx: WebSocketContext, message: String): Unit =
        ctx.send(s"echo: ${message}")
      override def onBinaryMessage(ctx: WebSocketContext, message: Array[Byte]): Unit =
        ctx.send(message)
      override def onClose(ctx: WebSocketContext): Unit =
        println("connection closed")
      override def onError(ctx: WebSocketContext, e: Throwable): Unit =
        println(s"error: ${e.getMessage}")
  }
  .start()

WebSocketHandler Callbacks ​

CallbackWhen it fires
onOpen(ctx)After the handshake completes, before any message
onTextMessage(ctx, message)A complete text message arrived
onBinaryMessage(ctx, message)A complete binary message arrived
onClose(ctx)The connection closed (client- or server-initiated); delivered exactly once
onClose(ctx, statusCode, reason)The same event, with the close status; its default calls onClose(ctx). See Close Status
onError(ctx, e)A callback or the connection raised an error

WebSocketContext ​

The ctx passed to each callback controls the connection. Its send/close methods are safe to call from any thread:

scala
ctx.request                      // the original HTTP upgrade request
ctx.send("hello")                // send a text message
ctx.send(Array[Byte](1, 2, 3))   // send a binary message
ctx.close()                      // close with 1000 (normal closure)
ctx.close(1001, "going away")    // close with a status code and reason

A reason longer than 123 UTF-8 bytes is cut to fit a close frame, and a code that may not be sent is sent as 1011. A client that stops reading is dropped (16 MiB of queued sends on Netty and Node, a 30 s stalled send on the built-in and Native servers), and onClose reports 1013. See Slow Peers.

Allowed Origins ​

Before the route filter runs, the server checks the browser Origin of the upgrade. Same-origin pages and clients that send no Origin are accepted; any other origin gets 403. Allow a front end served from another origin (e.g. a Vite dev server) explicitly:

scala
Http
  .server
  .withPort(8080)
  .withAllowedOrigins("http://localhost:5173", "https://app.example.com")
  .withWebSocketRoute("/ws") { _ => handler }

Gating the Upgrade With a Filter ​

Pass an RxHttpFilter to authenticate or otherwise gate the upgrade handshake. A 2xx response allows the upgrade; a non-2xx response (or an empty Rx) rejects it. Attributes the filter adds to the request are visible via ctx.request:

scala
import wvlet.uni.http.{Response, RxHttpFilter, WebSocketContext, WebSocketHandler}
import wvlet.uni.http.Http
import wvlet.uni.rx.Rx

val authFilter = RxHttpFilter { (request, next) =>
  request.header("Authorization") match
    case Some(token) if isValid(token) =>
      next.handle(request.addHeader("X-User", userOf(token)))
    case _ =>
      Rx.single(Response.unauthorized)
}

Http
  .server
  .withPort(8080)
  .withWebSocketRoute("/ws/secure", authFilter) { request =>
    new WebSocketHandler:
      override def onOpen(ctx: WebSocketContext): Unit =
        ctx.send(s"hello ${ctx.request.header("X-User").getOrElse("anonymous")}")
  }
  .start()

Readable Rejections ​

Node.js and browser clients can't read the HTTP status of a rejected upgrade: they report it as close 1006 with no status, the same as a network failure. To let a client tell "not allowed" from "network down", register the route with withCloseOnRejection(). A filter rejection then accepts the upgrade and closes at once with code 4000 + the HTTP status, and the response body as the reason:

scala
import wvlet.uni.http.WebSocketRoute

Http
  .server
  .withPort(8080)
  .withWebSocketRoute(
    WebSocketRoute("/ws/secure", _ => handler, authFilter).withCloseOnRejection()
  )
  .start()
Filter resultClose code
Response.unauthorized (401)4401
Response.forbidden (403)4403
An empty Rx4403
A filter errorits error response, usually 4500

The reason is cut to 123 UTF-8 bytes, and is the status phrase when the body is empty. The route's handler is never created for a rejected upgrade. The allowed-origins and host checks run before the filter and still answer plain HTTP 403, so a cross-site page never completes a handshake. Malformed upgrades (400, 426) stay HTTP errors too. Without withCloseOnRejection(), a rejection is a plain HTTP response, as before.

Relaying to an Upstream ​

WebSocketRelay pipes a session to an upstream WebSocket server, for example from a voice client to a model's realtime API. The route filter still decides who may connect; the relay opens the upstream with its own headers and reports each session's usage for metering:

scala
import wvlet.uni.http.{Request, WebSocketRelay, WebSocketRoute}

Http
  .server
  .withPort(8080)
  .withWebSocketRoute(
    WebSocketRoute(
      "/v1/realtime",
      request =>
        WebSocketRelay(
          Request.get("wss://api.example.com/v1/realtime").withBearerToken(apiKey)
        ).withStatsReporter { stats =>
          meter(request, stats.durationMillis, stats.bytesToUpstream)
        }.newHandler(),
      authFilter
    ).withCloseOnRejection()
  )
  .start()

See Relaying a Session for the queueing and close-code rules.

Frame Size ​

Inbound messages are aggregated from continuation frames up to a configurable limit (1 MB by default):

scala
Http
  .server
  .withWebSocketMaxFrameSize(4 * 1024 * 1024)  // 4 MB
  .withWebSocketRoute("/ws") { _ => new WebSocketHandler {} }
  .start()

WebSocket routes coexist with REST endpoints on the same server and port. For connecting to a WebSocket endpoint, see the cross-platform WebSocket Client.

Combining Controllers ​

Combine multiple controllers into a single router:

scala
class UserController:
  @Endpoint(HttpMethod.GET, "/users")
  def listUsers(): String = "[]"

class ItemController:
  @Endpoint(HttpMethod.GET, "/items")
  def listItems(): String = "[]"

val router = Router.of[UserController]
  .andThen(Router.of[ItemController])

val handler = RouterHandler(router)

Example: Complete REST API ​

scala
import wvlet.uni.http.{HttpMethod, Request, Response}
import wvlet.uni.http.router.{Endpoint, Router}
import wvlet.uni.http.RxHttpFilter
import wvlet.uni.http.Http
import wvlet.uni.http.router.RouterHandler
import wvlet.uni.rx.Rx

case class User(id: String, name: String)

class UserController:
  private var users = Map(
    "1" -> User("1", "Alice"),
    "2" -> User("2", "Bob")
  )

  @Endpoint(HttpMethod.GET, "/users")
  def listUsers(): Seq[User] = users.values.toSeq

  @Endpoint(HttpMethod.GET, "/users/:id")
  def getUser(id: String): Response =
    users.get(id) match
      case Some(user) => Response.ok.withJsonContent(s"""{"id":"${user.id}","name":"${user.name}"}""")
      case None => Response.notFound(s"User ${id} not found")

  @Endpoint(HttpMethod.POST, "/users")
  def createUser(request: Request): Response =
    // Parse and create user
    Response.created.withJsonContent("""{"id":"3","name":"New User"}""")

  @Endpoint(HttpMethod.DELETE, "/users/:id")
  def deleteUser(id: String): Response =
    users -= id
    Response.noContent

val loggingFilter = RxHttpFilter { (request, next) =>
  val start = System.currentTimeMillis()
  next.handle(request).map { response =>
    val duration = System.currentTimeMillis() - start
    println(s"${request.method} ${request.path} -> ${response.status} (${duration}ms)")
    response
  }
}

val router = Router.of[UserController]
val handler = RouterHandler(router)

Http
  .server
  .withPort(8080)
  .withFilter(loggingFilter)
  .withRxHandler(handler)
  .start { server =>
    println(s"API running at http://localhost:${server.localPort}")
    Thread.currentThread().join()  // Run indefinitely
  }

Released under the Apache 2.0 License.