From 88bef6c2ef33d120f1284968e452f6162a6972d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6ren=20Maschmann?= <44289172+DontMash@users.noreply.github.com> Date: Wed, 25 Mar 2026 19:49:01 +0100 Subject: [PATCH] docs: add example for session management (#3594) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves: #1216 --------- Co-authored-by: Bartek IwaƄczuk Co-authored-by: Claude Opus 4.6 (1M context) --- docs/latest/examples/session-management.md | 63 ++++++++++++++++++++++ docs/toc.ts | 1 + 2 files changed, 64 insertions(+) create mode 100644 docs/latest/examples/session-management.md diff --git a/docs/latest/examples/session-management.md b/docs/latest/examples/session-management.md new file mode 100644 index 00000000..f61c8d6d --- /dev/null +++ b/docs/latest/examples/session-management.md @@ -0,0 +1,63 @@ +--- +description: | + How to manage a session using cookies. +--- + +A _session_ allows you to keep track of per-user state such as authentication or +shopping cart contents. Cookies are the most common mechanism for session +management. Since [Deno](https://deno.com) uses standard web APIs like `Request` +and `Response`, working with cookies is straightforward. + +## Setup + +Add the `@std/http` package from the standard library: + +```sh +deno add jsr:@std/http +``` + +## Solution + +Use a middleware to assign each visitor a session ID stored in a cookie. The +middleware reads the existing cookie from the request, or generates a new one, +and makes it available to downstream routes via `ctx.state`. + +```ts main.ts +import { getCookies, setCookie } from "@std/http"; + +interface SessionState { + session: string; +} + +app.use(async (ctx: Context) => { + const cookies = getCookies(ctx.req.headers); + const session = cookies["session"]; + ctx.state.session = session ?? crypto.randomUUID(); + + const response = await ctx.next(); + + // Set the cookie for new sessions + if (!session) { + setCookie(response.headers, { + name: "session", + value: ctx.state.session, + path: "/", + httpOnly: true, + sameSite: "Lax", + }); + } + + return response; +}); + +app.get("/", (ctx: Context) => { + return new Response(`Your session ID is: ${ctx.state.session}`); +}); +``` + +> [info]: This is a basic implementation. In production you would typically +> store session data in a database keyed by the session ID, and add a +> `secure: true` attribute when serving over HTTPS. + +For more background, see the +[MDN guide on HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies). diff --git a/docs/toc.ts b/docs/toc.ts index a7409594..8e394958 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -100,6 +100,7 @@ const toc: RawTableOfContents = { "link:latest", ], ["active-links", "Active links", "link:latest"], + ["session-management", "Session management", "link:latest"], ], }, },