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:
- Assign the property directly.
- Use
setoraddto 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
- Cookie Attribute Config – detailed configuration options.
- Open in Markdown – view the original Markdown source for this page.
- Interactive Playground – try the example live.