All files / apps/web/src/utils cookies.ts

62.5% Statements 5/8
50% Branches 1/2
33.33% Functions 1/3
71.42% Lines 5/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            332x     4776x   332x                   332x               6x                      
import { createServerOnlyFn } from "@tanstack/react-start";
import type { SerializeOptions } from "cookie";
import { parse, serialize } from "cookie";
 
import type { UnauthorizedContext } from "~web/handlers/context";
 
export const getCookie = (
	cookieHeader: string | null,
	cookieName: string,
): string | undefined => parse(cookieHeader ?? "")[cookieName];
 
const DEFAULT_SET_COOKIE_OPTIONS: SerializeOptions = {
	httpOnly: true,
	path: "/",
	sameSite: "strict",
};
 
type Options = Omit<SerializeOptions, "expires"> & {
	expires: Temporal.ZonedDateTime;
};
 
export const getOptions = ({ expires, ...opts }: Options) => ({
	...DEFAULT_SET_COOKIE_OPTIONS,
	// It seems to be the simplest way to comply with the library
	// oxlint-disable-next-line eslint-js/no-restricted-syntax
	expires: new Date(expires.toInstant().epochMilliseconds),
	...opts,
});
 
export const setCookie = createServerOnlyFn(
	(
		{ resHeaders }: Pick<UnauthorizedContext, "resHeaders">,
		cookieName: string,
		cookieValue: string,
		opts: Options,
	) => {
		const newCookie = serialize(cookieName, cookieValue, getOptions(opts));
		resHeaders.set("Set-Cookie", newCookie);
	},
);