|
| 1 | +import { createIsomorphicFn } from '@tanstack/start-client-core' |
| 2 | +import { |
| 3 | + getCookie as getServerCookie, |
| 4 | + setCookie as setServerCookie, |
| 5 | +} from '@tanstack/start-server-core' |
| 6 | +import { parse, serialize } from 'cookie-es' |
| 7 | +import type { CookieSerializeOptions } from 'cookie-es' |
| 8 | + |
| 9 | +type GetCookieFn = (name: string) => string | undefined |
| 10 | +type SetCookieFn = ( |
| 11 | + name: string, |
| 12 | + value: string, |
| 13 | + options?: CookieSerializeOptions, |
| 14 | +) => void |
| 15 | + |
| 16 | +/** |
| 17 | + * Get a cookie value by name. Works on both the server (reads the current |
| 18 | + * request's `Cookie` header) and the client (reads `document.cookie`). |
| 19 | + * @param name Name of the cookie to get |
| 20 | + * @returns Value of the cookie, or `undefined` if not present |
| 21 | + * ```ts |
| 22 | + * const authorization = getCookie('Authorization') |
| 23 | + * ``` |
| 24 | + */ |
| 25 | +export const getCookie: GetCookieFn = createIsomorphicFn() |
| 26 | + .server(getServerCookie) |
| 27 | + .client((name: string) => parse(document.cookie)[name]) as GetCookieFn |
| 28 | + |
| 29 | +/** |
| 30 | + * Set a cookie value by name. Works on both the server (sets a `Set-Cookie` |
| 31 | + * header on the current response) and the client (writes `document.cookie`). |
| 32 | + * @param name Name of the cookie to set |
| 33 | + * @param value Value of the cookie to set |
| 34 | + * @param options Options for serializing the cookie |
| 35 | + * ```ts |
| 36 | + * setCookie('Authorization', '1234567') |
| 37 | + * ``` |
| 38 | + */ |
| 39 | +export const setCookie: SetCookieFn = createIsomorphicFn() |
| 40 | + .server(setServerCookie) |
| 41 | + .client((name: string, value: string, options?: CookieSerializeOptions) => { |
| 42 | + document.cookie = serialize(name, value, options) |
| 43 | + }) as SetCookieFn |
0 commit comments