Elm Ports: Type-Safe JavaScript Interop Without Breaking Purity
Use Elm ports to exchange JSON-safe data with JavaScript while keeping Elm's pure core intact.
11 Dec 2025, 11:09 UTC

Use Elm ports when you need JavaScript, not Elm flags
Elm programs are pure: the update function cannot reach out to localStorage, call an analytics endpoint, or initialize a third-party widget directly. If your application needs to talk to JavaScript, Elm's supported escape hatch is a port. A port is a typed, one-way channel between Elm and JavaScript. Every value crossing it must be JSON-serializable, so the Elm compiler rejects non-serializable payloads before you ever run the code.
The useful takeaway: declare ports in a dedicated port module, send data from Elm as a Cmd msg, receive data in Elm as a Sub msg, and handle the messages in update like any other Elm message. Do not assume messages arrive in order or synchronously.
A Cmd msg is a command: a description of a side effect the Elm runtime performs after update. A Sub msg is a subscription: a stream of external messages Elm delivers to update. A port module is a file flagged with the port keyword that is allowed to declare ports.
Worked configuration: a counter that talks to JavaScript
This example assumes Elm 0.19. It sends the current count to JavaScript whenever it changes, and lets JavaScript push a new count back into Elm.
1. Create the port module
Ports must live in a module declared with port module. You cannot mix port declarations with ordinary declarations in the same file.
port module Ports exposing (..)
port countToJS : Int -> Cmd msg
port fromJS : (Int -> msg) -> Sub msg
Where to run: create src/Ports.elm in your Elm project root. No special permissions are required. countToJS is an outgoing port: Elm produces an Int and JavaScript consumes it. fromJS is an incoming port: JavaScript sends an Int, and Elm turns it into a message.
2. Wire the ports into Main.elm
module Main exposing (..)
import Browser
import Html exposing (button, div, text)
import Html.Events exposing (onClick)
import Ports exposing (..)
type Msg
= Increment
| Decrement
| FromJS Int
update : Msg -> Int -> ( Int, Cmd Msg )
update msg model =
case msg of
Increment ->
( model + 1, Ports.countToJS (model + 1) )
Decrement ->
( model - 1, Ports.countToJS (model - 1) )
FromJS n ->
( n, Ports.countToJS n )
subscriptions : Int -> Sub Msg
subscriptions _ =
Ports.fromJS FromJS
view : Int -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (String.fromInt model) ]
, button [ onClick Increment ] [ text "+" ]
]
init : () -> ( Int, Cmd Msg )
init _ =
( 0, Cmd.none )
main : Program () Int Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
Expected check: elm make src/Main.elm --output=main.js should compile without errors. The generated main.js exposes the port bindings through the Elm program object.
3. Connect from JavaScript
var app = Elm.Main.init({ node: document.getElementById('app') });
app.ports.fromJS.send(41);
app.ports.countToJS.subscribe(function (count) {
console.log('Elm count:', count);
});
Where to run: load the compiled page in a browser and open the developer console. Required permission: none beyond normal page execution. Risk: sending values faster than Elm can process them can queue messages; ports are asynchronous and unordered, so do not use them for a strict request-response protocol.
What the compiler allows and rejects
Elm serializes port payloads to JSON. Allowed types include Int, Float, Bool, String, List, Array, Maybe, Result, tuples up to three elements, records, and custom types with a single constructor carrying serializable fields. The compiler rejects functions, Task, Process, Html msg, and opaque types with a compile-time error.
Limits and common mistakes
- One-way and asynchronous. An outgoing port is a
Cmd, not a function that returns a value. An incoming port is aSub, not a callback you can await insideupdate. Design handlers to be idempotent. port moduleis mandatory. Elm 0.19 does not allow ad-hoc ports inMain. If you try to declareportoutside aport module, compilation fails.- No functions across the boundary. Declaring
port bad : (Int -> Int) -> Cmd msgproduces a compiler error about non-serializable types. Wrap behavior in messages instead. - JSON serialization overhead. Large or high-frequency payloads (for example, every mouse movement) can bottleneck the boundary. Batch updates or use a canvas/WebGL approach for graphics-heavy data.
Verify the result
- Run
elm make src/Main.elm --output=main.jsin the project root and confirm a clean exit. - Open the page, open the browser console, and run
app.ports.fromJS.send(42). Confirm the Elm view updates to42. - Click the increment button and confirm the console logs the new count from
countToJS.subscribe. - Attempt to add
port bad : (Int -> Int) -> Cmd msgtoPorts.elmand confirm the compiler rejects it; remove the line before committing.
Ports keep Elm's purity intact while giving you a controlled door to JavaScript. Treat them as asynchronous, typed message queues—not synchronous function calls—and your interop will stay predictable.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.