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 = Request

An incoming HTTP request.

Examples

requestHeader req "content-type"

Response

type Response = Response

An HTTP response.

Examples

empty 204 []

Server

type Server = Server

A configured HTTP server ready to run under a supervisor.

Examples

serve (\_ -> empty 204 [])

Config

type Config = Config

HTTP listener configuration.

Examples

defaultConfig
    |> httpPort 3000

Values

serve

serve : (Request -> Response) -> Server

Serve HTTP requests with a handler.

Examples

serve (\_ -> empty 204 [])

serveWithSupervisor

serveWithSupervisor : Builder -> (Request -> Response) -> Server

Serve HTTP requests under an existing supervisor tree.

Examples

serveWithSupervisor (Supervisor.new OneForOne) handle

application

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 msg

HTTP 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 : Config

The default HTTP server configuration.

Examples

defaultConfig

httpPort

httpPort : Int -> Config -> Config

Set the HTTP listen port.

Examples

httpPort 3000 defaultConfig

maxBodySize

maxBodySize : Int -> Config -> Config

Maximum request body size in bytes (default 2_000_000, clamped to 1 GiB).

Examples

maxBodySize 5_000_000 defaultConfig

bodySpoolThreshold

bodySpoolThreshold : Int -> Config -> Config

Bodies larger than this (default 262_144) are spooled to a temp file.

Examples

bodySpoolThreshold 1_000_000 defaultConfig

tlsCert

tlsCert : String -> Config -> Config

PEM certificate file for HTTPS. Pair with tlsKey; both are required to enable TLS (Cowboy start_tls).

Examples

tlsCert "cert.pem" defaultConfig

tlsKey

tlsKey : String -> Config -> Config

PEM private key file for HTTPS. Pair with tlsCert.

Examples

tlsKey "key.pem" defaultConfig

supervised

supervised : Config -> ChildSpecification Server

Child specification for the HTTP listener.

Examples

supervised (httpPort 3000 defaultConfig)

html

html : Int -> List Header -> Html msg -> Response

Return an HTML document response.

Examples

html 200 [] (Html.text "hi")

string

string : Int -> List Header -> String -> String -> Response

Return a raw string body with an explicit content type.

Examples

string 200 [] "text/plain" "ok"

empty

empty : Int -> List Header -> Response

Return an empty body.

Examples

empty 204 []

json

json : a -> Response

Encode a value as JSON (thoas) and return it as a 200 response.

Examples

json { count = 1 }

jsonStatus

jsonStatus : Int -> a -> Response

Encode a value as JSON with an explicit status code.

Examples

jsonStatus 201 { id = 1 }

jsonField

jsonField : Request -> String -> Maybe a

Decode a JSON object field from the request body.

Examples

jsonField req "email"

jsonAt

jsonAt : Request -> List String -> Maybe a

Decode a nested JSON path from the request body.

Examples

jsonAt req [ "user", "email" ]

body

body : Request -> Bytes

The full request body as Bytes. Prefer bodyLines / bodyStream for large uploads.

Examples

body req

bodyStream

bodyStream : Int -> Request -> Stream Bytes

Lazily stream the request body as fixed-size byte chunks.

Examples

bodyStream 65536 req

bodyLines

bodyLines : Request -> Stream String

Lazily stream the request body as newline-delimited lines.

Examples

bodyLines req

requestHeader

requestHeader : Request -> String -> Maybe String

Read one request header (name matched case-insensitively).

Examples

requestHeader req "authorization"

cookies

cookies : Request -> Cookies

The full cookie jar from the request.

Examples

cookies req

pageHtml

pageHtml : String -> String -> String -> String

SPA 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 } -> String

SPA 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 -> Response

Serve a packaged SPA asset for the request path.

Examples

asset req

assetUrl

assetUrl : String

URL path of the packaged SPA JS (/_/<hash>.js).

Examples

assetUrl

static

static : String -> String -> Response

Serve 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.url

corsHeaders

corsHeaders : String -> List Header

CORS 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 Header

CORS 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 -> Response

204 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 -> Response

204 preflight when origin is in allowed.

Examples

corsPreflightAllowlist [ "https://a.example" ] "https://a.example"

withCors

withCors : String -> Response -> Response

Prepend 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 -> Response

Prepend allowlisted CORS headers onto an existing response.

Examples

withCorsAllowlist [ "https://a.example" ] "https://a.example" (json {})

withHeaders

withHeaders : List Header -> Response -> Response

Prepend response headers onto an existing response.

Examples

withHeaders [ header "x-request-id" id ] (empty 200 [])

newRequestId

newRequestId : String

A fresh opaque request id (UUID v4 string) for correlation headers.

Examples

newRequestId