Reference · Cookies and sessions

cookie

signature
cookie(str) -> str | null

What it does

The value of a cookie the browser sent with the request, decoded, or null when there is none of that name. It works in any function the request runs (a route, a server fn, a helper, a pipeline stage), so a helper that reads the visitor's time zone need not be handed request. request.cookies is all of them as a map. A page that reads either is the visitor's, sent with Cache-Control: private and Vary: Cookie (since 0.7: one that read request.cookies was not). Outside a request (a job, a script) it is null. See Headers, cookies and sessions.

Examples

in a program
route GET / = <Page theme={cookie("theme") ?? "light"}><Home/></Page>fn visitor_zone() = cookie("tz") ?? "UTC"route GET /agenda = <Agenda zone={visitor_zone()} items={today(visitor_zone())}/>

The whole round: a page whose form sets the cookie with set_cookie, and reads it back on the next visit. After Save with dark, the answer carries set-cookie: theme=dark; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax, and the page comes back as <body class="dark"> with dark selected:

in a program
route GET / {    let theme = cookie("theme") ?? "light"    <body class={theme}>        <form method="post" action="/theme">            <select name="theme">                <option selected={theme == "light"}>light</option>                <option selected={theme == "dark"}>dark</option>            </select>            <button>Save</button>        </form>    </body>}route POST /theme { form: { theme: str } } { set_cookie("theme", theme, { max_age: "1y" }); redirect("/") }
print(cookie("theme"))print(cookie("theme") ?? "light")
output
nulllight

Edge cases

print(cookie("count"), int(cookie("count") ?? "0"))set_cookie("count", "1")print(cookie("count"))
output
null 0null

Errors

A name that is not a string, or no name, is a runtime error, not an error value. An unknown name is not an error: it is null.

this one fails
print(cookie(42))
output
line 1: `cookie` expects a cookie's name, got int

Chaining

A cookie's value is text, so it starts a pipeline of conversions, with the default given first:

print(cookie("page") ?? "1" | int)print(cookie("tags") ?? "a,b" | split(",") | map(upper))
output
1["A", "B"]

See also

set_cookie, delete_cookie, session, int

Thread
8Useful? Like it, or add to its thread below.

Thread 0 posts

On cookie(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo