Why port functions are not defined?


While trying myself to implement a port as exposed here, I couldn’t find a way to know why port functions are not defined; actually, the elm linter told me that (kudos for the linter tho!!).

Therefore, why is that any common function must have a declaration whereas port function don’t? How does it work then? Does it just work with JSON-encoded values? Where can I get more info. on how Cmd msg?

Thanks in advance! :smile:

1 Like

You don’t implement the port in Elm code, because the whole point is to allow access to running/receiving data from JavaScript.

If you want an example of this, Massive Decks (Elm side, JS—well, in this case TypeScript—side) uses ports for a number of features via web APIs that Elm doesn’t currently expose.

1 Like

Hey @espetro :wave:

Trying to implement an app with ports?

I have an example here for how to use ports with Elm:

Why don’t ports have a declaration?

I think what you’re asking is why don’t ports look like this:

port outgoing : String -> Cmd msg
port outgoing =

Like normal Elm functions. The reason is that you’ll define the behavior of the Port in JS.

In Elm, you only need to declare the name (“outgoing”) and the type of data you want to send ("String").

After you implement the JS, your port will work!

Does it just work with JSON encoded values?

Yep! You can encode your data as a string, or any of the types listed here:

More info about Cmd Msg

A command (Cmd) is the way Elm allows our init or update function to return a “side-effect”.

A side-effect can be sending like sending an HTTP request to an API, or communicating with JavaScript via ports. It’s for doing things other than returning pure data.

For ports to work, let’s make sure we do these three things:

  1. Use port module instead of module at the top of the file.
  2. Declare a port like this: port outgoing : String -> Cmd msg
  3. Handle it in your JavaScript code:
app.ports.outgoing.subscribe( function (message) {

If you have more questions on ports, come join the official Elm slack!

You can join us here: https://elmlang.herokuapp.com/

The #beginners and #general channel are great places to ask questions :smiley:

Hope that helps!


Thanks @RyanNHG @Latty for the answers! Both are quite clarifying :grin::grin:

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.