Cookie
Read and update cookies through the cookie object in your handler.
Extract a cookie by name, then use .value to read or replace its value.
import { Elysia } from 'elysia'
new Elysia() .get('/', ({ cookie: { name } }) => { // Get name.value
// Set name.value = "New Value" })Elysia encodes and decodes object values for you, so you can work with a cookie as an object.
Reactivity
Section titled “Reactivity”Changing a cookie’s value or attributes schedules a Set-Cookie header on the response. You don’t need to assemble the header yourself.
The cookie jar is a proxy. Reading a name returns a Cookie object; reading .value gives you its value. Iterating the jar visits existing cookie names.
Cookie Interaction
Section titled “Cookie Interaction”Cookies can be interacted with in two ways:
- Set a property directly.
- Use
setorupdateto update several properties.
See cookie attribute config for more information.
Assign property
Section titled “Assign property”Read or assign cookie attributes like normal object properties. Elysia uses the updated attributes when it writes the cookie.
import { Elysia } from 'elysia'
new Elysia() .get('/', ({ cookie: { name } }) => { // get name.domain
// set name.domain = 'millennium.sh' name.httpOnly = true })set builds a new cookie property object from its initial properties and current value, then applies the properties you provide. Use update when you want to merge into the current properties.
import { Elysia } from 'elysia'
new Elysia() .get('/', ({ cookie: { name } }) => { name.set({ domain: 'millennium.sh', httpOnly: true }) })update
Section titled “update”Use update to merge attributes into the current cookie without resetting the other properties. Older documentation called this operation add; the Elysia 2 method is update.
import { Elysia } from 'elysia'
new Elysia() .get('/', ({ cookie: { name } }) => { name.update({ httpOnly: true }) })remove
Section titled “remove”Call .remove() to expire a cookie. Use the same path and domain with which it was set. If the cookie has no value, remove() does nothing.
The JavaScript expression delete cookie.name does not expire a browser cookie in Elysia 2. Use .remove() so the response carries the expiration attributes.
import { Elysia } from 'elysia'
new Elysia() .get('/', ({ cookie: { name } }) => { name.remove() })Cookie schema
Section titled “Cookie schema”Use cookie to validate incoming cookie values and infer their types in the handler. Both t.Cookie() and t.Object() are supported, and additional cookie names are allowed by default.
Read or update a validated cookie through its .value property. This example requires an existing name cookie with the specified object shape.
import { Elysia, t } from 'elysia'
new Elysia() .get('/', { cookie: t.Cookie({ name: t.Object({ id: t.Numeric(), name: t.String() }) }) }, ({ cookie: { name } }) => { // Set name.value = { id: 617, name: 'Summoning 101' } })Optional cookie
Section titled “Optional cookie”Wrap a cookie field in t.Optional to allow the cookie to be absent. This allows undefined; use t.Nullable when you want to accept null.
import { Elysia, t } from 'elysia'
new Elysia() .get('/', { cookie: t.Cookie({ name: t.Optional( t.Object({ id: t.Numeric(), name: t.String() }) ) }) }, ({ cookie: { name } }) => { // Set name.value = { id: 617, name: 'Summoning 101' } })Cookie specs
Section titled “Cookie specs”A cookie is a small value the browser stores and sends with matching requests. Use it for state that needs to travel with the client, such as a session identifier.
Browser fetch manages the Cookie header itself. Use credentials when the request needs the browser’s cookies:
fetch('http://localhost:3000/cookie', { credentials: 'include'})The browser’s cookie and cross-origin rules still apply.
t.Cookie
Section titled “t.Cookie”t.Cookie() describes an object of cookie values and accepts cookie-specific options as its second argument:
import { Elysia, t } from 'elysia'
new Elysia() .get('/cookie', { cookie: t.Cookie({ name: t.String() }, { secure: true, httpOnly: true }) }, ({ cookie }) => cookie.name.value)secure and httpOnly configure cookies sent by the server; they aren’t properties you can prove about an incoming cookie string.
Cookie signature
Section titled “Cookie signature”A cookie signature lets Elysia verify that a cookie value was signed with your secret and has not been changed. Elysia signs outgoing values and verifies incoming signatures automatically.
Signing does not encrypt the value. The client can still read its contents.
Using cookie signatures
Section titled “Using cookie signatures”Provide secrets and use sign to select the cookie names to sign and verify. The profile cookie below is optional so a first request can create it.
Elysia signs the updated profile and checks its signature on later requests. The example secret is illustrative; keep your real signing secret private.
import { Elysia, t } from 'elysia'
new Elysia() .get('/', { cookie: t.Cookie({ profile: t.Optional(t.Object({ id: t.Numeric(), name: t.String() })) }, { secrets: 'Fischl von Luftschloss Narfidort', sign: ['profile'] }) }, ({ cookie: { profile } }) => { profile.value = { id: 617, name: 'Summoning 101' } })Constructor
Section titled “Constructor”Set cookie.secrets and cookie.sign in the Elysia constructor to share signing configuration across routes.
import { Elysia, t } from 'elysia'
new Elysia({ cookie: { secrets: 'Fischl von Luftschloss Narfidort', sign: ['profile'] }}) .get('/', { cookie: t.Cookie({ profile: t.Optional(t.Object({ id: t.Numeric(), name: t.String() })) }) }, ({ cookie: { profile } }) => { profile.value = { id: 617, name: 'Summoning 101' } })Cookie rotation
Section titled “Cookie rotation”Elysia handles cookie secret rotation automatically.
Put the new secret first and keep previous secrets after it. Elysia verifies incoming signatures against every entry and signs new values with the first one, which must be a non-empty string.
import { Elysia } from 'elysia'
new Elysia({ cookie: { secrets: ['Vengeance will be mine', 'Fischl von Luftschloss Narfidort'] }})Unsigned cookie transition
Section titled “Unsigned cookie transition”Elysia supports graceful transition from unsigned to signed cookies.
By setting null in an array of cookie.secrets, Elysia will allow unsigned cookies to pass through while checking invalid cookie signatures when available.
Elysia signs new cookie values with the first entry, so keep null after the signing secret.
Remove null after the transition so unsigned cookies are rejected.
import { Elysia } from 'elysia'
new Elysia({ cookie: { secrets: ['Vengeance will be mine', 'Fischl von Luftschloss Narfidort', null] }})Config
Section titled “Config”Use these options in the constructor or in t.Cookie. All of them except secrets and sign can also be passed when updating cookie attributes; signing is configured on the app or the route, not on a single write.
secrets
Section titled “secrets”The key used to sign and verify cookies. The option is named secrets, not secret.
Accepts a string or an array of strings. An array enables key rotation. In the constructor, secrets may also be, or include, null to permit unsigned cookies during a transition; t.Cookie does not accept null.
domain
Section titled “domain”Specifies the value for the Domain Set-Cookie attribute.
By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
encode
Section titled “encode”Elysia 2 does not expose a custom encode cookie option. Cookie values are encoded during serialization; assign the value through .value.
expires
Section titled “expires”Specifies the Date object to be the value for the Expires Set-Cookie attribute.
By default, no expiration is set, and most clients will consider this a “non-persistent cookie” and will delete it on conditions like exiting a web browser application.
httpOnly
Section titled “httpOnly”Default: false.
Specifies the boolean value for the HttpOnly Set-Cookie attribute.
When truthy, the HttpOnly attribute is set. Otherwise, it is not.
By default, the HttpOnly attribute is not set.
maxAge
Section titled “maxAge”Default: undefined.
Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute.
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
Specifies the value for the Path Set-Cookie attribute.
When path is omitted, Elysia sets Path=/, so the cookie is available across the site.
priority
Section titled “priority”Specifies the string to be the value for the Priority Set-Cookie attribute.
low will set the Priority attribute to Low.
medium will set the Priority attribute to Medium, the default priority when not set.
high will set the Priority attribute to High.
More information about the different priority levels can be found in the specification.
sameSite
Section titled “sameSite”Specifies the boolean or string to be the value for the SameSite Set-Cookie attribute.
true will set the SameSite attribute to Strict for strict same-site enforcement.
false will not set the SameSite attribute.
'lax' will set the SameSite attribute to Lax for lax same-site enforcement.
'none' will set the SameSite attribute to None for an explicit cross-site cookie.
'strict' will set the SameSite attribute to Strict for strict same-site enforcement.
More information about the different enforcement levels can be found in the specification.
secure
Section titled “secure”Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set. Otherwise, it is not. By default, the Secure attribute is not set.