Middleware is a function fn that applies to all requests. The user can introspect the headers (and only the headers) of the requests in order to add information (such as the connected user if a field in the headers provides such information). This information added to the request can be retrieved from the request handlers via Request.get.
Here is an example of middleware confirming client authentication via the "Authorization" field:
let ( let* ) = Option.bind
let decode str =
match String.split_on_char ' ' str with
| [ "Basic"; b64 ] ->
let data = Base64.decode b64 in
let* data = Result.to_option data in
let data = String.split_on_char ':' data in
let username = List.hd data and password = List.tl data in
let password = String.concat ":" password in
Some (username password)
| _ -> None
let auth =
VIf.Middlewares.v ~name:"auth" @@ fun req _target _server _ ->
let hdrs = Vif.Request.headers_of_request req in
let* value = Vif.Headers.get hdrs "Authorization" in
let* username, password = decode value in
Some (username, password)
let () =
Miou_unix.run @@ fun () ->
let middlewares = Vif.Middlewares.[ auth ] in
Vif.run ~middlewares routes ()