npm.io
2.0.4 • Published 1 year ago

svelte-baked-cookie

Licence
MIT
Version
2.0.4
Deps
4
Size
10 kB
Vulns
0
Weekly
0
DeprecatedThis package is deprecated

npm-version npm-license npm-download-month npm-min-size ci.yml website

Universal accessible hard-baked cookies for SvelteKit

Demo

From a single schema, type-defined cookies can be accessed in any environment.

Installation

npm i svelte-baked-cookie

Usage

  1. Use the bakery function to define the cookie type and get bake and rebake. See ts-serde for more information on type guard
// bakery.js
import { bakery } from 'svelte-baked-cookie'
import { json, number, string } from 'svelte-baked-cookie/serde'

export const { bake, rebake } = bakery(
  {
    key1: string,
    key2: number,
    key3: json(
      (x): x is string[] =>
        Array.isArray(x) && x.every((y) => typeof y === 'string'),
      []
    )
  }
  // {
  //   CookieSetOptions: (optional)
  // }
)
  1. In the server, you can get a typed accessor by passing a cookies object obtained from load, etc. to the bake function.
// +layout.server.js
import { bake } from './bakery.js'

export const load = ({ cookies }) => {
  const { bakedCookies } = bake(cookies)

  // string
  const str = bakedCookies.key1

  // number
  const num = bakedCookies.key2

  // string[]
  bakedCookies.key3 = ['value', 'set', 'by', 'server']

  return {
    // ...
  }
}
  1. On the client, the rebake function can be used directly to obtain a writable svelte-store of typed cookies.
<!-- +page.svelte -->
<script>
  import { rebake } from './bakery.js'

  const cookies = rebake()

  // key1: string
  // key2: number
  // key3: string[]

  // string
  console.log(cookies.key1)

  // string
  cookies.key2 = 123

  // string[]
  cookies.key3 = ['value', 'set', 'by', 'client']
</script>
  1. (optional): When using SSRs, this may not be sufficient.
    When rendering svelte components on the server, the server's cookie cannot be accessed directly, which may result in display flickering.
    To solve this, you need to pass the cookie pie from +layout.server.js, etc. and make it the dough of rebake .
// +layout.server.ts
import { bake } from './bakery.js'

export const load = ({ cookies }) => {
  const { bakedCookies, pie } = bake(cookies)

  // ...

  return {
    pie
  }
}
<!-- +layout.svelte -->
<script>
  import { rebake } from './bakery.js'

  let { data } = $props()

  let pie = $derived(data.pie)

  // key1: string
  // key2: number
  // key3: string[]
  let cookies = $derived(rebake(pie))
</script>

This is optional, but it provides full consistency and typed cookie access to the application.

License

MIT