useCookie()
Reads and writes cookies reactively, working on both server and client.
Syntax
const cookie = useCookie(name, options?) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
name | string | Yes | The cookie name. |
options | CookieOptions | No | `default`, `maxAge`, `expires`, `path`, `domain`, `secure`, `httpOnly`, `sameSite`, `watch`, `readonly`, `encode`, `decode`. |
Returns
Ref<T> — A ref synced to the cookie; assigning updates the cookie.
Examples
<script setup lang="ts">
const theme = useCookie('theme', { default: () => 'light' })
function toggle() {
theme.value = theme.value === 'light' ? 'dark' : 'light'
}
</script>
<script setup lang="ts">
const token = useCookie('token', {
maxAge: 60 * 60 * 24 * 7,
sameSite: 'lax',
secure: true,
})
</script>
Notes
On SSR the cookie is read from the request and writes update the
Set-Cookie header. `httpOnly` cookies cannot be read in the browser.
The ref auto-serializes objects to JSON. After a server-side write you
may need `refreshCookie` to sync the client value within the same
request lifecycle.