Cookies

Bind Vue state to cookies, readable by the server.

useCookies binds state to a cookie. Cookies can be read by server, which makes them ideal for values that affect SSR: locale, theme, feature flags. Changes are picked up across tabs via the Cookie Store API where available.

<script setup lang="ts">
import {  } from 'kvantjs/vue'
import * as  from 'kvantjs/schema'

const  = ('locale', .().('en'))
</script>

<template>
  < ="">
    < ="en">English</>
    < ="de">Deutsch</>
  </>
</template>

Setting a key to undefined removes its entry. Values equal to the schema default are never written. Defaults stay internal. Multiple composables bound to the same key stay in sync automatically.

Key maps work too:

const  = ({
  : .().('en'),
  : .(['light', 'dark']).('light'),
})

. = { ...., : 'dark' }
.. = 'dark' // deeply reactive!

Options

Options extend the standard Set-Cookie attributes:

Prop

Type

const  = (
  'consent',
  .().(false),
  { : 60 * 60 * 24 * 365, : 'lax' },
)

Set options once for a component subtree using the provide function:

<script setup lang="ts">
import {  } from 'kvantjs/vue'

({ : 60 * 60 * 24 * 365, : 'lax' })
</script>

SSR setup

When rendering on the server (or prerendering), document.cookie is unavailable. Provide the request's Cookie header as a fallback with the provide function in a top-level component:

<script setup lang="ts">
import {  } from 'kvantjs/vue'

const : string = '...' // comes from your server entry, e.g. via SSR context

({ :  })
</script>

With the fallback in place, the first client render matches the server-rendered HTML, with no hydration mismatch.

On this page