svelte-baked-cookie

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

🍪 Universal accessible hard-baked cookies for SvelteKit

▷ Installation

Render by server

key1: key2: key3: []
// 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'),
      []
    )
  },
  {
    path: '/',
    secure: false
  }
)
// +layout.server.js
import { bake } from 'bakery.js'

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

  bakedCookies.key3.set(['value', 'set', 'by', 'server'])

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

  export let data

  $: ({ pie } = data)

  $: cookies = rebake(pie)
  $: ({ key1, key2, key3 } = cookies)
</script>

<main>
  <code>key1: <input bind:value={$key1} /></code>
  <code>key2: <input bind:value={$key2} type="number" /></code>
  <code>key3: {JSON.stringify($key3)}</code>
</main>