Reference · Cookies and sessions

session

signature
session() -> map

What it does

The visitor's session: the map set_session stored, read from the signed cookie the browser sent back, or {} when there is none. It works in any function the request runs: a route, a server fn a component calls, a helper, a pipeline stage. Outside a request (a job, a script) it is {}. See Headers, cookies and sessions.

Examples

in a program
route GET /me {    let id = session().user ?? reply 401 "Log in first"    db.one("select id, name from users where id = ?", id)}server fn save_note(text: str) {    let id = session().user ?? return err("Sign in first")    db.exec("insert into notes (user_id, text) values (?, ?)", id, text)}
print(session())print(session().user)print(session().user ?? "nobody")
output
{}nullnobody

Edge cases

print(session() == {}, len(keys(session())))set_session({ user: 7, role: "admin" })print(session(), session().role)end_session()print(session())
output
true 0{ user: 7, role: "admin" } admin{}

Errors

session() takes no arguments and never fails: a missing, expired or forged cookie is {}. Guarding a route is the program's own ??:

let id = session().user ?? "guest"print(id)
output
guest
in a program
fn me() = session().user == null ? null : db.one("select id, name from users where id = ?", session().user)fn me_or_login(back: str) = me() ?? reply 303 redirect(`/login?next=${url_encode(back)}`)

Chaining

The map is a value like any other: a field, a default, a lookup.

set_session({ user: 7, roles: ["editor", "admin"] })print(session().roles | map(upper))print(session() | keys)
output
["EDITOR", "ADMIN"]["user", "roles"]

See also

set_session, end_session, cookie, unwatched

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

Thread 0 posts

On session(): 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