---
title: "Cookie"
description: "Learn how to manage cookies in Elysia, including setting, retrieving, and securing cookies for your web applications."
url: "https://next.elysiajs.com/tutorial/patterns/cookie/"
---

# Cookie

You interact with cookies by using [cookie](/patterns/cookie/) from context.

```typescript
import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { visit } }) => {
    visit.value = Number(visit.value ?? 0) + 1

    return `You have visited ${visit.value} times`
  })
  .listen(3000)
```

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.

```typescript
import { Elysia, t } from 'elysia'

new Elysia()
  .get('/', {
    cookie: t.Object({
      visit: t.Optional(
        t.Object({
          total: t.Number()
        })
      )
    })
  }, ({ cookie: { visit } }) => {
    visit.value ??= { total: 0 }
    visit.value.total++

    return `You have visited ${visit.value.total} times`
  })
  .listen(3000)
```

We can use [cookie schema](/patterns/cookie/#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.

```typescript
import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ cookie: { visit } }) => {
    visit.value = Number(visit.value ?? 0) + 1

    visit.httpOnly = true
    visit.path = '/'

    visit.set({
      sameSite: 'lax',
      secure: true,
      maxAge: 60 * 60 * 24 * 7
    })

    return `You have visited ${visit.value} times`
  })
  .listen(3000)
```

See [Cookie attribute](/patterns/cookie/#assign-property).

## Remove

We can remove cookie by calling `.remove()` method.

```typescript
import { Elysia } from 'elysia'

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

    return `Cookie removed`
  })
  .listen(3000)
```

## Cookie signature

Elysia can sign cookies to prevent tampering by:

1. Provide a cookie secret to the Elysia constructor.
2. Use `t.Cookie` to provide secret for each cookie.

```typescript
import { Elysia, t } from 'elysia'

new Elysia({
  cookie: {
    secrets: 'Fischl von Luftschloss Narfidort',
  }
})
  .get('/', {
    cookie: t.Cookie({
      visit: t.Optional(t.Number())
        }, {
            secrets: 'Fischl von Luftschloss Narfidort',
            sign: ['visit']
        })
  }, ({ cookie: { visit } }) => {
    visit.value ??= 0
    visit.value++

    return `You have visited ${visit.value} times`
  })
  .listen(3000)
```

If multiple secrets are provided, Elysia will use the first secret to sign cookies, and try to verify with the rest.

See [Cookie signature](/patterns/cookie/#cookie-signature), [Cookie rotation](/patterns/cookie/#cookie-rotation).

## Assignment

Let’s create a simple counter that tracks how many times you have visited the site.
