Server-rendered pages in your elm-pages
can set cookies. elm-pages
provides two high-level ways to work with cookies:
Server.Session.withSession
provides a high-level way to manage key-value pairs of data using cookie storage,
whereas Server.Response.withSetCookieHeader
gives a more low-level tool for setting cookies. It's often best to use the
most high-level tool that will fit your use case.
You can learn more about the basics of cookies in the Web Platform in these helpful MDN documentation pages:
The default option in this API is for HttpOnly cookies https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly.
Cookies can be exposed so you can read them from JavaScript using Document.cookie
. When this is intended and understood
then there's nothing unsafe about that (for example, if you are setting a darkMode
cookie and what to access that
dynamically). In this API you opt into exposing a cookie you set to JavaScript to ensure cookies aren't exposed to JS unintentionally.
In general if you can accomplish your goal using HttpOnly cookies (i.e. not using makeVisibleToJavaScript
) then
it's a good practice. With server-rendered elm-pages
applications you can often manage your session state by pulling
in session data from cookies in a BackendTask
(which is resolved server-side before it ever reaches the browser).
Secure (only sent over https, or localhost on http) is the default. This overrides that and
removes the Secure
attribute from the cookie.
The default SameSite policy is Lax if one is not explicitly set. See the SameSite section in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes.
Usually you'll want to use Server.Response.withSetCookieHeader
instead.
This is a low-level helper that's there in case you want it but most users will never need this.