Server
HTML & web
HTTP servers on the BEAM.
Start with serve for a plain Request -> Response handler, or application when you also want an init / update / subscriptions program beside the listener (in-memory state, timers, mailboxes). Each request still runs in its own process; see the Language docs under HTTP + OTP.
Large uploads: set maxBodySize on Config, then fold bodyStream / bodyLines (or Multipart.fileStream) with Stream.tryFoldl / Stream.stoppableFoldl inside handle. Do not use attemptFoldl on HTTP body streams: tasks run after the response is sent. body / jsonAt / Multipart.parse still force a full read (memory or spool) when needed.
Types
Request
type Request = RequestAn incoming HTTP request.
Examples
requestHeader req "content-type"Response
type Response = ResponseAn HTTP response.
Examples
empty 204 []Server
type Server = ServerA configured HTTP server ready to run under a supervisor.
Examples
serve (\_ -> empty 204 [])Config
type Config = ConfigHTTP listener configuration.
Examples
defaultConfig
|> httpPort 3000Header
type alias Header =
(String, String)A response header as a name/value pair.
Examples
header "content-type" "text/plain"Values
serve
serve : (Request -> Response) -> ServerServe HTTP requests with a handler.
Examples
serve (\_ -> empty 204 [])serveWithSupervisor
serveWithSupervisor : Builder -> (Request -> Response) -> ServerServe HTTP requests under an existing supervisor tree.
Examples
serveWithSupervisor (Supervisor.new OneForOne) handleapplication
application : { init : flags -> (model, Cmd msg) , update : msg -> model -> (model, Cmd msg) , subscriptions : model -> Sub msg , handle : Request -> Response , supervisor : Builder , config : Config } -> Program flags model msgHTTP handlers stay concurrent. The program beside them holds in-memory state.
Own Port / Mcp / Acp sessions from init on that program. Request processes reach them with Process.send / Process.call; do not open ports, MCP, or ACP from handle.
Examples
application
{ init = init
, update = update
, subscriptions = subscriptions
, handle = handle
, supervisor = Supervisor.new OneForOne
, config = defaultConfig |> httpPort 3000
}defaultConfig
defaultConfig : ConfigThe default HTTP server configuration.
Examples
defaultConfighttpPort
httpPort : Int -> Config -> ConfigSet the HTTP listen port.
Examples
httpPort 3000 defaultConfigmaxBodySize
maxBodySize : Int -> Config -> ConfigMaximum request body size in bytes (default 2_000_000, clamped to 1 GiB).
Examples
maxBodySize 5_000_000 defaultConfigbodySpoolThreshold
bodySpoolThreshold : Int -> Config -> ConfigBodies larger than this (default 262_144) are spooled to a temp file.
Examples
bodySpoolThreshold 1_000_000 defaultConfigtlsCert
tlsCert : String -> Config -> ConfigPEM certificate file for HTTPS. Pair with tlsKey; both are required to enable TLS (Cowboy start_tls).
Examples
tlsCert "cert.pem" defaultConfigtlsKey
tlsKey : String -> Config -> ConfigPEM private key file for HTTPS. Pair with tlsCert.
Examples
tlsKey "key.pem" defaultConfigsupervised
supervised : Config -> ChildSpecification ServerChild specification for the HTTP listener.
Examples
supervised (httpPort 3000 defaultConfig)html
html : Int -> List Header -> Html msg -> ResponseReturn an HTML document response.
Examples
html 200 [] (Html.text "hi")string
string : Int -> List Header -> String -> String -> ResponseReturn a raw string body with an explicit content type.
Examples
string 200 [] "text/plain" "ok"empty
empty : Int -> List Header -> ResponseReturn an empty body.
Examples
empty 204 []json
json : a -> ResponseEncode a value as JSON (thoas) and return it as a 200 response.
Examples
json { count = 1 }jsonStatus
jsonStatus : Int -> a -> ResponseEncode a value as JSON with an explicit status code.
Examples
jsonStatus 201 { id = 1 }jsonField
jsonField : Request -> String -> Maybe aDecode a JSON object field from the request body.
Examples
jsonField req "email"jsonAt
jsonAt : Request -> List String -> Maybe aDecode a nested JSON path from the request body.
Examples
jsonAt req [ "user", "email" ]body
body : Request -> BytesThe full request body as Bytes. Prefer bodyLines / bodyStream for large uploads.
Examples
body reqbodyStream
bodyStream : Int -> Request -> Stream BytesLazily stream the request body as fixed-size byte chunks.
Examples
bodyStream 65536 reqbodyLines
bodyLines : Request -> Stream StringLazily stream the request body as newline-delimited lines.
Examples
bodyLines reqheader
header : String -> String -> HeaderBuild a response header.
Examples
header "set-cookie" cookieValuerequestHeader
requestHeader : Request -> String -> Maybe StringRead one request header (name matched case-insensitively).
Examples
requestHeader req "authorization"cookie
cookie : Request -> String -> Maybe StringRead a single cookie from the request.
Examples
cookie req "u"cookies
cookies : Request -> CookiesThe full cookie jar from the request.
Examples
cookies reqpageHtml
pageHtml : String -> String -> String -> StringSPA shell HTML: HTML-escapes title, validates the module name (letters/digits/dots), and inserts flags as already-JSON (with </ neutralized). Empty #app; prefer page when the same TEA view should SSR for hydrate.
Examples
pageHtml "App" "Main" "{}"page
page : { title : String , module_ : String , flags : String , body : Html msg } -> StringSPA shell with SSR markup inside #app plus JSON flags for client init.
module_ is the JS export path (Main, App, ...). body should be the same view the client will hydrate (Browser.element into #app). Event attributes are inert until JS boots.
Examples
page
{ title = "App"
, module_ = "Main"
, flags = "{}"
, body = Html.text ""
}asset
asset : Request -> ResponseServe a packaged SPA asset for the request path.
Examples
asset reqassetUrl
assetUrl : StringURL path of the packaged SPA JS (/_/<hash>.js).
Examples
assetUrlstatic
static : String -> String -> ResponseServe a file under root for a URL path (query string stripped).
Rejects path traversal (.., absolute escapes). Missing or unsafe paths return 404. Directories try index.html. MIME type is guessed from the extension.
Examples
Server.static "static" "/img/logo.png"
Server.static "static" req.urlcorsHeaders
corsHeaders : String -> List HeaderCORS headers for one trusted/fixed origin.
Do not pass a reflected request Origin (for example from Server.requestHeader req "origin"). That turns CORS into an open relay. Use a compile-time constant here, or corsAllowlist when the value comes from the client.
Examples
corsHeaders "https://example.com"corsAllowlist
corsAllowlist : List String -> String -> List HeaderCORS headers when origin is in allowed; empty list otherwise.
Prefer this over corsHeaders whenever origin is read from the request. Reflecting an unchecked Origin into Access-Control-Allow-Origin is unsafe.
Examples
corsAllowlist [ "https://a.example" ] "https://a.example"corsPreflight
corsPreflight : String -> Response204 preflight response with CORS headers for a trusted/fixed origin.
Same rule as corsHeaders: fixed origin only, never a reflected request Origin.
Examples
corsPreflight "https://example.com"corsPreflightAllowlist
corsPreflightAllowlist : List String -> String -> Response204 preflight when origin is in allowed.
Examples
corsPreflightAllowlist [ "https://a.example" ] "https://a.example"withCors
withCors : String -> Response -> ResponsePrepend CORS headers for a trusted/fixed origin onto an existing response.
Same rule as corsHeaders: fixed origin only, never a reflected request Origin. Use withCorsAllowlist for request-supplied origins.
Examples
withCors "https://example.com" (empty 200 [])withCorsAllowlist
withCorsAllowlist : List String -> String -> Response -> ResponsePrepend allowlisted CORS headers onto an existing response.
Examples
withCorsAllowlist [ "https://a.example" ] "https://a.example" (json {})withHeaders
withHeaders : List Header -> Response -> ResponsePrepend response headers onto an existing response.
Examples
withHeaders [ header "x-request-id" id ] (empty 200 [])newRequestId
newRequestId : StringA fresh opaque request id (UUID v4 string) for correlation headers.
Examples
newRequestId