Nex.Cookie (nex_core v0.4.3)

Copy Markdown

Cookie read/write helpers for Nex actions and API handlers.

Cookies are set by storing pending cookie operations in the process dictionary. Nex.Handler applies them to the Plug.Conn response before sending.

Usage

# In a page action
def login(req) do
  token = req.body["token"]
  Nex.Cookie.put(:session_id, token, max_age: 86_400, http_only: true)
  Nex.redirect("/dashboard")
end

def logout(_req) do
  Nex.Cookie.delete(:session_id)
  Nex.redirect("/")
end

# Read cookies in mount/1 via params (cookies are in req.cookies for API,
# or use Nex.Cookie.get/1 in page mount)
def mount(params) do
  session_id = Nex.Cookie.get(:session_id)
  %{logged_in: session_id != nil}
end

Options for put/3

  • :max_age - Seconds until expiry (default: session cookie)
  • :http_only - Prevent JS access (default: true)
  • :secure - HTTPS only (default: false)
  • :same_site - "Strict", "Lax", or "None" (default: "Lax")
  • :path - Cookie path (default: "/")
  • :domain - Cookie domain (default: not set)

Summary

Functions

Returns all cookies from the current request as a map.

Applies all pending cookie operations to the Plug.Conn. Called by Nex.Handler before sending the response.

Clears pending cookie state from the process dictionary. Called by Nex.Handler after the response is sent.

Deletes a cookie by setting its max_age to 0.

Reads a cookie value from the current request.

Stores incoming cookies from the request in the process dictionary. Called by Nex.Handler at the start of each request.

Sets a cookie. The cookie is applied to the response by Nex.Handler.

Functions

all()

Returns all cookies from the current request as a map.

apply_to_conn(conn)

Applies all pending cookie operations to the Plug.Conn. Called by Nex.Handler before sending the response.

clear_process_state()

Clears pending cookie state from the process dictionary. Called by Nex.Handler after the response is sent.

delete(name, opts \\ [])

Deletes a cookie by setting its max_age to 0.

get(name, default \\ nil)

Reads a cookie value from the current request.

Returns nil if the cookie is not present. Cookies are populated by Nex.Handler at the start of each request.

load_from_conn(conn)

Stores incoming cookies from the request in the process dictionary. Called by Nex.Handler at the start of each request.

put(name, value, opts \\ [])

Sets a cookie. The cookie is applied to the response by Nex.Handler.