The language

You already met the core syntax in the Language tour. This page is about building real apps: HTTP servers on the BEAM, and the Workers path when target = "javascript".

App modules (server, database, shared views, and client SPAs) are .selm. Community packages you download from the Elm registry under project elm-stuff stay .elm.

Coming from Elm? See Differences from Elm for OR-patterns, guards, value patterns, [glsl| … |] on JS, :=, and the other forms we added. Migration modules, erlang/elixir FFI, and := are BEAM-only; WebGL shaders are JS-only.

HTTP + OTP

Think of Server.application as The Elm Architecture beside an HTTP listener. Every request gets its own process and calls handle. That keeps routes concurrent. The program holds short-lived in-memory state. Durable data stays in the database.

Routes that never touch the program do not share a bottleneck. Process.send does not wait. Process.call waits only for that one message (with a timeout). Slow work that changes the model is Task.attempt. Work that touches no model is Task.spawn.

main : Program () Model Msg
main =
    Server.application
        { init = init
        , update = update
        , subscriptions = subscriptions
        , handle = handle
        , supervisor = Supervisor.new OneForOne |> Supervisor.add (Repo.supervised repo)
        , config = Server.defaultConfig
        }

handle req =
    case Server.Route.parse route req of
        Increment ->
            let
                _ =
                    Process.send (Process.namedSubject mailbox) Increment
            in
            Server.empty 204 []

        Count ->
            Server.string 200 [] "text/plain"
                (String.fromInt (Process.call (Process.namedSubject mailbox) 5000 GetCount))

        NotFound ->
            Server.empty 404 []

Prefer a handler with no program? Use Server.serve. Need a supervisor tree that already contains the listener? Use serveWithSupervisor. Field names like httpPort, dbPort, and dbName avoid the Elm keywords port and database. Set Repo.user, Repo.password, and Repo.dbName in your app.

Cross-cutting concerns (CORS, request logging, request ids) wrap handle with Server.Middleware.run before Server.Route.parse. See Conduit's Router for the usual stack. Middleware.cors / Server.corsHeaders take a fixed origin; use corsAllowlist when the value comes from the request Origin header (never reflect that header unchecked).

To call another HTTP service (or your own server from a CLI.* task), use Req.get / Req.post and friends. Req is the outbound client; Server is the listener.

Workers Server (JavaScript)

With target = "javascript" and main : Server.Program, the same Server.application + Supervisor shape runs on Cloudflare Workers. The gate is the Worker fetch handler: TEA init / update / subscriptions are isolate-local (Server.send / Server.snapshot from handle). Cmd / Sub effect managers beyond Cmd.none / Sub.none are not wired yet.

Each Server.durable child is a Durable Object: sticky identity, single-threaded mailbox, versioned model storage with a migrate hook, and Server.Crash restarts. Mailbox JSON codecs (encodeMsg / decodeMsg / model / reply) are derived when omitted; write them explicitly when you need a fixed wire shape. Answer calls with Server.reply (like Process.reply). Bad mailbox codecs return HTTP 400 without clearing storage.

Server.callMap Counter.subject 5000 (\r -> Counter.Get r)
    (\n -> Server.text 200 (String.fromInt n))

-- Get reply ->
--     Server.reply count reply count

call / tryCall / callMap / askMap match BEAM Process.call: a timeout in milliseconds and a reply Subject injected into msg. Decode that subject with Server.replySubject; use Server.noReply when casting a message that embeds a reply slot. Gate→DO transport prefers stub selmMailbox RPC. The synthetic fetch mailbox is an internal fallback only (path + token); Durable Object fetch otherwise handles WebSocket upgrades. Never proxy a raw client Request onto stub fetch for call/cast/restart.

Nest with Supervisor.supervised / startChild. Restart intensity is Supervision.Restart via Server.withRestart (Temporary skips peer clears on Workers; Transient behaves like Permanent). Children talk with Server.askMap / Server.cast from onMessage (same-object re-entry is Reentrant). Extra ids under a worker kind: Server.instance worker "room-42". Placement: Server.locationHint / Server.jurisdiction. Public HTTP into a DO: Server.forward + withFetch.

Alarms: scheduleIn / cancelAlarm / onAlarm, plus getAlarm and alarmInfo for peek and retry metadata. Beside the model envelope, Server.Storage uses storage.kv (selm/ keys reserved; survives Crash). Worker secrets / KV / R2 / Queues are Server.Env. Optional SQL: unrestricted database module tables and Repo.transaction run on SQLite-backed objects (new_sqlite_classes); use Database.Sql for DDL and ad-hoc SQL. Sequences, cookie policies, and compile-time SQL planning stay on the BEAM.

Realtime rooms: Server.Socket.supervised + Server.Channel.define on hibernatable WebSockets (acceptWebSocket / webSocketMessage). Channel JSON codecs are hand-written on Workers (BEAM still derives binary wire from a channel module).

Keep Server.binding aligned with wrangler.toml (selm wrangler init / selm wrangler check). Walk through examples/21_durable_counter and examples/22_durable_chat, or use plain Fetch.Handler in examples/20_cloudflare_worker when you do not need sticky state.

See How it works for the BEAM vs Workers state table. API reference lives in runtime/server/*.selm (Workers) beside stdlib Server (BEAM).

Channels

Channels are typed websockets. On the BEAM, a channel module declares the topic, the messages the browser sends (Up), the messages the server pushes (Down), and the join reply — the compiler derives the binary codecs. Socket.supervised mounts the websocket. On Workers, use Server.Socket.supervised + Server.Channel.define with explicit JSON codecs instead (see below and examples/22_durable_chat).

On the SPA side, treat three kinds of messages separately: the socket connection, admission to one topic, and the topic protocol itself.

channel : Channel Topic Up Down Reply State Msg
channel =
    Channel.define
        { join = join
        , handleIn = handleIn
        , update = update
        , subscriptions = subscriptions
        }
Socket.connect socket GotSocket
Socket.listen socket Chat.channel Chat.Lobby
    { access = GotRoom
    , receive = GotChat
    }

GotSocket is Connecting, Open, Reconnecting, Unauthorized, or Stale. GotRoom is Ok reply or Err refusal. GotChat carries only Chat.Down. See examples/05_chat for a lobby with no database.

On Workers, handleIn returns downs to broadcast; hibernation uses Durable Object acceptWebSocket / webSocketMessage. Channel JSON derive is not available yet — keep the codecs on Server.Channel.define.

To stream uploads (CSV rows, records, or raw Bytes), put chunk and finish constructors on Up, warn with an error Down as soon as a chunk fails, and send a final finished Down after commit. Call StreamUpload.handleIn from your channel handleIn (same knot-tying as Channel.broadcast channel). Bytes is wire-safe, so opaque binary chunks work the same way as structured rows. See examples/14_ws_books_upload.

If you know Lamdera: Up is ToBackend, Down is ToFrontend, Socket.push is sendToBackend, and handleIn is updateFromFrontend. Keep dual programs and wire ADTs; do not try to run the same client Msg on the server.

Database modules

A database module is where you declare tables, row security, indexes, and the functions that run inside Repo.transaction. The := binding marks a resource the runtime owns for you (a table, a sequence, a checked-out row).

database module Todos exposing (getTodos, addTodo)

import Cookies exposing (Cookies)
import Database.Security as Security
import Database.Sequence as Seq exposing (Sequence)
import Database.Table exposing (..)
import Users exposing (UserID)

type TodoID = TodoID UInt64

type alias Todo =
  { id : TodoID
  , owner : UserID
  , title : String
  , completed : Bool
  }

todos : Table UserID Todo
todos :=
  table
    { primary = .id
    , security =
        Security.policy
          { access = \user todo -> todo.owner == user
          , insert = \user todo -> todo.owner == user
          , update = \user before after -> before.owner == user && after.owner == user
          , remove = \user todo -> todo.owner == user
          }
    , indexes = [ concurrently (btree NotUnique .owner) ]
    , constraints = [ foreignKey .owner Users.referencesUserID ]
    }

todoIDs : Sequence TodoID
todoIDs :=
  Seq.uint64 TodoID

getTodos : Cookies -> Transaction (Rows TodoInfo)
getTodos cookies =
  let
    user :=
      Users.requireSession cookies
  in
  access todos user
    |> map (\todo -> { id = todo.id, title = todo.title, completed = todo.completed })
    |> selectAll

Call these from HTTP handlers inside Repo.transaction, usually with Server.cookies. Every select / selectAll needs a map first: that projection is what the query returns. Indexes: btree Unique .field or btree NotUnique .field. Wrap one in concurrently (...) for CREATE INDEX CONCURRENTLY.

Named Repos and Cache

You can run more than one connection pool. Repo.name registers a pool; "default" keeps selm_default_repo. Repo.schemaOwner marks which pool runs migrations. Talk to a named pool with Repo.on "name".

repo =
  Repo.postgres
    |> Repo.name "primary"
    |> Repo.schemaOwner True
    |> Repo.poolSize 8

cache =
  Repo.ets
    |> Repo.name "cache"

case Repo.on "cache" (Cache.set "session" token) of
  Ok () ->
    Server.empty 204 []

  Err _ ->
    Server.empty 500 []

SQLite works like Postgres: Repo.sqlite |> Repo.path "app.sqlite". Valkey is a cache peer of ETS: Repo.valkey |> Repo.host "127.0.0.1" (optional Repo.password, Repo.dbName for the Valkey DB index) behind the same Cache API.

Migrations

Schema changes are planned, not improvised. Put ordered migration modules in src/migrations/. They run first. Afterwards selm reconciles the live database with the generated models.json (create/add/index and safe widens; never an automatic DROP).

migration module RenameTodoTitle exposing (plan)

import Database.Migration as Migration exposing (Plan)

plan : Plan
plan =
  Migration.id "20261031_rename_todo_title"
    |> Migration.renameColumn "todos" "title" "label"

Erlang / Elixir externals

Need a BEAM library? Bind it with an external. The type annotation is yours; the implementation is the Erlang or Elixir function.

decode : String -> Value
decode =
  erlang "thoas" "decode"

encode : a -> String
encode =
  elixir "Jason" "encode!"

elixir "Module" "fun" compiles to 'Elixir.Module':fun/arity. Install Elixir only if you use it. The Elm port keyword is not supported here.