import { type CookieMapOptions } from "https://deno.land/x/frugal@0.5.0/docs/dep/std/http.ts";
Provides a iterable map interfaces for managing cookies server side.
Examples
To access the keys in a request and have any set keys available for creating a response:
import {
CookieMap,
mergeHeaders
} from "https://deno.land/std@0.224.0/http/cookie_map.ts";
const request = new Request("https://localhost/", {
headers: { "cookie": "foo=bar; bar=baz;"}
});
const cookies = new CookieMap(request, { secure: true });
console.log(cookies.get("foo")); // logs "bar"
cookies.set("session", "1234567", { secure: true });
const response = new Response("hello", {
headers: mergeHeaders({
"content-type": "text/plain",
}, cookies),
});
To have automatic management of cryptographically signed cookies, you can use
the SecureCookieMap
instead of CookieMap
. The biggest
difference is that the methods operate async in order to be able to support
async signing and validation of cookies:
import {
SecureCookieMap,
mergeHeaders,
type KeyRing,
} from "https://deno.land/std@0.224.0/http/cookie_map.ts";
const request = new Request("https://localhost/", {
headers: { "cookie": "foo=bar; bar=baz;"}
});
// The keys must implement the `KeyRing` interface.
declare const keys: KeyRing;
const cookies = new SecureCookieMap(request, { keys, secure: true });
console.log(await cookies.get("foo")); // logs "bar"
// the cookie will be automatically signed using the supplied key ring.
await cookies.set("session", "1234567");
const response = new Response("hello", {
headers: mergeHeaders({
"content-type": "text/plain",
}, cookies),
});
In addition, if you have a Response
or Headers
for a
response at construction of the cookies object, they can be passed and any
set cookies will be added directly to those headers:
import { CookieMap } from "https://deno.land/std@0.224.0/http/cookie_map.ts";
const request = new Request("https://localhost/", {
headers: { "cookie": "foo=bar; bar=baz;"}
});
const response = new Response("hello", {
headers: { "content-type": "text/plain" },
});
const cookies = new CookieMap(request, { response });
console.log(cookies.get("foo")); // logs "bar"
cookies.set("session", "1234567");
Properties
The Response
or the headers that will be used with the
response. When provided, Set-Cookie
headers will be set in the headers
when cookies are set or deleted in the map.
An alternative way to extract the headers is to pass the cookie map to the
mergeHeaders
function to merge various sources of the
headers to be provided when creating or updating a response.