aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/.server/cookie.ts
blob: c8365ebc5eba7f668a428d5931b1ff8f960aa4b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { parse as parseCookie, serialize as serializeCookie } from "cookie";
import { Cookie, CookieOptions } from "react-router";

// Remix's createCookie() returns "structured" cookies, which are cookies that hold a JSON-encoded object.
// This is not suitable for interoperation with other systems that expect a simple string value.
// This function creates an "unstructured" cookie, a simple plain text.
export function createUnstructuredCookie(
	name: string,
	cookieOptions?: CookieOptions,
): Cookie {
	const { secrets = [], ...options } = {
		path: "/",
		sameSite: "lax" as const,
		...cookieOptions,
	};

	return {
		get name() {
			return name;
		},
		get isSigned() {
			return secrets.length > 0;
		},
		get expires() {
			return typeof options.maxAge !== "undefined"
				? new Date(Date.now() + options.maxAge * 1000)
				: options.expires;
		},
		async parse(cookieHeader, parseOptions) {
			if (!cookieHeader) return null;
			const cookies = parseCookie(cookieHeader, {
				...options,
				...parseOptions,
			});
			return name in cookies ? cookies[name] : null;
		},
		async serialize(value, serializeOptions) {
			return serializeCookie(name, value, {
				...options,
				...serializeOptions,
			});
		},
	};
}