Skip to content

Commit ebf543d

Browse files
committed
feat(vue-start): add isomorphic getCookie/setCookie to root export
1 parent a56a6eb commit ebf543d

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

packages/vue-start/src/cookies.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

packages/vue-start/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export { useServerFn } from './useServerFn'
2+
export { getCookie, setCookie } from './cookies'
23
export * from '@tanstack/start-client-core'
34
// Explicit re-exports shadow `export *` above so these public-API names are
45
// registered on the namespace at link time (via Vite SSR's `defineExport`

0 commit comments

Comments
 (0)