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+):
libraryDependencies += "org.wvlet.uni" %% "uni" % "2026.3.12"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:
| Platform | Backend for Http.server | Backend-only options |
|---|---|---|
| JVM | Netty when uni-netty is on the classpath, otherwise the built-in server (JDK 24+) | Netty.options (wvlet.uni.http.netty.Netty) |
| Scala.js | Node.js http | — (all settings are shared) |
| Scala Native | native sockets | Native.options (wvlet.uni.http.Native) |
A server that compiles and runs identically on every platform:
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:
.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 HttpServerOn 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:
// 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:
| Setting | Default | Ignored by |
|---|---|---|
withMaxContentLength(bytes) | 1 MiB (Netty: 64 KiB) | — |
withMaxInitialLineLength(bytes) | 4 KiB | Node.js (its maxHeaderSize covers the request line) |
withMaxHeaderSize(bytes) | 8 KiB (Node.js: 16 KiB) | — |
withRequestReadTimeoutMillis(ms) / noRequestReadTimeout | 30 s (Node.js: 300 s) | — |
withIdleTimeoutMillis(ms) | 30 s (Node.js: 5 s; Netty: the request read timeout covers it) | — |
withWriteTimeoutMillis(ms) / noWriteTimeout | 30 s (Netty: off) | Node.js |
withRequestDecompression / noRequestDecompression | on | Node.js (never decodes) |
withMaxDecompressedRequestSize(bytes) | 64 MiB | Node.js |
withMaxStreamingConnections(n) | 256 (Native: worker threads minus up to 4) | Node.js |
withShutdownTimeoutMillis(ms) | 30 s | Node.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:
// 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():
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:
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:
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.noContentOnly 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:
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:
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:
StringInt,Long,Short,ByteDouble,FloatBooleanOption[T]for optional parameters
Request Object Access
Add a Request parameter to access the full request:
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:
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 noContent-Type), and MessagePack (application/msgpackorapplication/x-msgpack). - Custom codecs: a
given Weaver[A]inA's companion object, or imported whereRouter.ofis called, is used when the parameter type isA, or a case class with anAfield. Weavers are resolved whenRouter.ofis compiled, so a given that is only in scope elsewhere is not seen. ForOption[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-
Optionobject parameter. A required body in another content type (e.g. a form post) returns 415. - A method that also takes
Requestmay 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 aContent-Typethat 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:
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-continuegets100 Continueonly when the handler first reads, so a filter that rejects the request (for example, a failed auth check) stops it before anything is uploaded. lengthis theContent-Length, or -1 for a chunked body.- The stream can be read from any thread until the response is sent; later reads throw
IOException. toContentBytesreads 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-Encodingand the bytes as sent. - Each upload takes a
withMaxStreamingConnectionsslot 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
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
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 ErrorResponse Content
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 headerResponse Conversion
Controller methods can return various types that are automatically converted to responses:
| Return Type | Conversion |
|---|---|
Response | Returned as-is |
Rx[Response] | Async response |
String | 200 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 |
Unit | 204 No Content |
| Other types | Serialized to JSON |
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:
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:
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
// 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:
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.
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.nameThe 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, ...):
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, andx-api-keyare logged as[redacted].withRedactedHeaders(...)replaces the list, andwithExcludedHeaders(...)leaves headers out.- A request that reaches an
@Endpointor RPC method also getsrpc_interface,rpc_class,rpc_method, andrpc_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 ofrpc_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 itstoString.Requestarguments are skipped.noRpcArgs()turnsrpc_argsoff. - 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. jsonFilewrites JSON lines with daily and size-based rotation. For Fluentd or another sink, implementHttpAccessLogWriter.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:
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
204withAccess-Control-Allow-Methods,-Headers,-Max-Age(600 s by default), and-Credentialswhen enabled. A preflight from a disallowed origin, or for a method or header the policy doesn't allow, gets403. - 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 ownVaryvalues), so a cache does not serve one origin's answer to another. WithwithAllowedOrigins("*")the answer is the same for every origin, andVaryis left alone. withAllowedOriginsmatches exactly, ignoring case and a trailing slash. For patterns, usewithOriginFilter(o => pattern.matches(o)), and anchor the pattern at the end soapp.example.com.evil.testdoes not match.withAllowedOrigins("*")answersAccess-Control-Allow-Origin: *. It cannot be combined withwithAllowCredentials(true):CorsFilterthrowsIllegalArgumentException.- By default a preflight may ask for any request header.
withAllowedHeaders(...)limits them, andwithExposedHeaders(...)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 itsexception_classandexception_message. The body is alwaysInternal Server Error, even withwithDetailedErrors; aServiceExceptionkeeps 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 afterCorsFilter(inside it): placed outside, it never sees an allowed origin's failure, whichCorsFilterhas already turned into a 500. - WebSocket upgrades are not affected; they use
withAllowedOriginson the server.
Server Configuration
Server Options
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
withMaxDecompressedRequestSizebytes (default 64 MiB) gets a plain-text413, 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. .noRequestDecompressionpasses 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:
| Default | Why | Opt out |
|---|---|---|
Bind to 127.0.0.1 | An 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 trace | Exception 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 403 | DNS 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 403 | Browsers attach cookies to cross-origin WebSocket handshakes (cross-site WebSocket hijacking) | .withAllowedOrigins("https://app.example.com"), or "*" for any origin |
| Bounded request size | A 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 parsing | A 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 connections | Idle 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 rejected | Prevents 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:
| Setting | Default | When 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 s | Keep 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) | 256 | The 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 check | Required behind a load balancer or in a container |
.withDetailedErrors(true) | off | Keep it off in production; the full exception is logged on the server |
Server Lifecycle
// 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 // falseBlock-based Server
For simpler use cases, use the block form that automatically stops the server:
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 hereSimple Handler
For simple cases without routing, use a direct handler:
Http
.server
.withPort(8080)
.withHandler { request =>
Response.ok(s"Hello from ${request.path}")
}
.start()Or with async responses:
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.
import wvlet.uni.http.{Http, StaticFiles}
Http
.server
.withPort(8080)
.withFilter(StaticFiles("dist").withSpaFallback(true))
.withRxHandler(api)
.start()| Request | Response |
|---|---|
GET /assets/app.js | The 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/users | Your handler |
GET /chats/42 from a browser, unknown to your handler | index.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 likeGIT~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 setsX-Content-Type-Options: nosniffso a browser never guesses a type. Add a type withwithContentType("glb", ContentType("model/gltf-binary")). - Caching: every file gets an
ETagfrom its size and modification time, andCache-Control: no-cache, so the browser revalidates on each load. A request whoseIf-None-Matchmatches gets304 Not Modifiedwithout the file being read, and a new build is picked up on the next load. Set another policy withwithCacheControl("max-age=3600"), or send none withnoCacheControl. - Range requests: every file response sends
Accept-Ranges: bytes. A single range (Range: bytes=0-1023,bytes=1024-, orbytes=-512) gets206 Partial Content, so a<video>can seek and a download can resume. A range that starts past the end gets416. Requests for several ranges get the whole file. WithIf-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.
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
| Callback | When 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:
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 reasonA 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:
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:
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:
import wvlet.uni.http.WebSocketRoute
Http
.server
.withPort(8080)
.withWebSocketRoute(
WebSocketRoute("/ws/secure", _ => handler, authFilter).withCloseOnRejection()
)
.start()| Filter result | Close code |
|---|---|
Response.unauthorized (401) | 4401 |
Response.forbidden (403) | 4403 |
An empty Rx | 4403 |
| A filter error | its 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:
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):
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:
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
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
}