Last active
February 17, 2024 16:41
-
-
Save cdoremus/17e35a72d118b5b6843a1d5838d8927e to your computer and use it in GitHub Desktop.
Deno Fresh Middleware for setting a session token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Fresh Middleware for setting a random sesssion token that can be picked up by Fresh route handlers. | |
Adopted from a Discord post by Chris Knight (@cknight): https://discord.com/channels/684898665143206084/991511118524715139/1202394052604215397 | |
Import map set in deno.json: | |
"imports": { | |
"$fresh/": "https://deno.land/x/[email protected]/", | |
"$std/": "https://deno.land/[email protected]/" | |
}, | |
*/ | |
import { FreshContext } from "$fresh/server.ts"; | |
import { getCookies, setCookie } from "$std/http/cookie.ts"; | |
interface State { | |
session: string; | |
} | |
export async function handler(req: Request, ctx: FreshContext<State>) { | |
if (ctx.destination === "route") { | |
const cookies = getCookies(req.headers); | |
let session = cookies.session; | |
if (session) { | |
ctx.state.session = cookies.session; | |
} else { | |
session = crypto.randomUUID(); | |
ctx.state.session = session; | |
} | |
const resp = await ctx.next(); | |
if (!cookies.session) { | |
setCookie(resp.headers, { | |
name: "session", | |
value: session, | |
httpOnly: true, | |
secure: true, | |
}); | |
} | |
return resp; | |
} | |
const resp = await ctx.next(); | |
return resp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment