Reactive Cookie - ElysiaJS | ElysiaJS

ID: 2116https://elysiajs.com/patterns/cookie.html
Source

Reactive Cookie – A modern, signal‑based API for working with HTTP cookies in Elysia.


Cookie

Elysia provides a mutable signal for interacting with cookies.
There are no getCookie or setCookie helpers – you work directly with the cookie object and its properties.

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { name } }) => {
    // Get
    name.value

    // Set
    name.value = 'New Value'
  })

By default the cookie signal automatically encodes/decodes objects, so you can treat cookies as plain JavaScript objects without worrying about serialization.


Reactivity

The cookie signal is reactive: changing its value automatically updates the Set-Cookie header.
The cookie value is never undefined – it’s a Cookie<unknown> object, accessed via the .value property.

You can treat the cookie jar as a plain object; iterating over it only yields existing cookie values.


Cookie Attribute

You can set cookie attributes in two ways:

  1. Assign the property directly.
  2. Use set or add to update multiple properties at once.

See the cookie attribute config for more details.

Assign Property

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { name } }) => {
    // Get
    name.domain

    // Set
    name.domain = 'millennium.sh'
    name.httpOnly = true
  })

set

set allows updating all attributes of a cookie in a single operation:

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { name } }) => {
    name.set({
      domain: 'millennium.sh',
      httpOnly: true
    })
  })

add

add behaves like set but only overwrites the properties you specify, leaving the rest intact.


remove

To delete a cookie, either call remove on the cookie or use the delete operator:

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { name } }) => {
    name.remove()
    // or
    delete cookie.name
  })

Cookie Schema

You can validate cookie values and get type inference using t.Cookie:

import { Elysia, t } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { name } }) => {
    // Set
    name.value = {
      id: 617,
      name: 'Summoning 101'
    }

    // Example of reading the typed value
    const payload = name.value
    // payload is inferred to have shape { id: number; name: string }
  }, {
    // Provide a schema for the cookie
    cookie: {
      name: t.Cookie({
        id: t.Integer(),
        name: t.String()
      })
    }
  })

(Note: the above snippet demonstrates how to use a cookie schema in a handler; the actual schema definition and usage may vary based on your application.)


References