Cookie
You interact with cookies by using cookie from context.
import { Elysia } from 'elysia'
.get('/', ({ cookie: { visit } }) => {
visit.value = Number(visit.value ?? 0) + 1
return `You have visited ${visit.value} times`
Cookie is a reactive object. Once modified, it will be reflected in response.
Value
Elysia will then try to coerce it into its respective value when a type annotation if provided.
import { Elysia, t } from 'elysia'
}, ({ cookie: { visit } }) => {
visit.value ??= { total: 0 }
return `You have visited ${visit.value.total} times`
We can use cookie schema to validate and parse cookie.
Attribute
We can get/set cookie attribute by its respective property name.
Otherwise, use .set() to bulk set attribute.
import { Elysia } from 'elysia'
.get('/', ({ cookie: { visit } }) => {
visit.value = Number(visit.value ?? 0) + 1
return `You have visited ${visit.value} times`
See Cookie attribute.
Remove
We can remove cookie by calling .remove() method.
import { Elysia } from 'elysia'
.get('/', ({ cookie: { visit } }) => {
Cookie signature
Elysia can sign cookies to prevent tampering by:
- Provide a cookie secret to the Elysia constructor.
- Use
t.Cookie to provide secret for each cookie.
import { Elysia, t } from 'elysia'
secrets: 'Fischl von Luftschloss Narfidort',
visit: t.Optional(t.Number())
secrets: 'Fischl von Luftschloss Narfidort',
}, ({ cookie: { visit } }) => {
return `You have visited ${visit.value} times`
If multiple secrets are provided, Elysia will use the first secret to sign cookies, and try to verify with the rest.
See Cookie signature, Cookie rotation.
Assignment
Let’s create a simple counter that tracks how many times you have visited the site.