İçeriğe geç

Cookie Management with Astro

You can use the cookie module to work with cookies in Astro. This module can be used to read, write, and delete cookies.

Astro.cookie.set('name', 'value', { expires: 7, path: '/' });

In this example, a cookie named name is created and the value value is assigned to it. This cookie will be valid for 7 days and will be accessible on all pages.

Astro.cookie.get('name');

In this example, the value of the cookie named name is retrieved.

Astro.cookie.delete('name');

In this example, the cookie named name is deleted.

Astro.cookie.has('name');

In this example, it is checked whether the cookie named name exists.

Astro.cookie.merge('name', 'value', { expires: 7, path: '/' });

In this example, a cookie named name is created and the value value is assigned to it. If a cookie with the name name already exists, the value of this cookie is updated.

Examples

Counter example:

---
let counter = Astro.cookie.get('counter') || 0;
if (Astro.cookie.has('counter')){
const cookie = Astro.cookie.get('counter');
const value = cookie?.number();
if(value !== undefined && !isNaN(value)) counter = value + 1;
}
Astro.cookie.set('counter',String(counter), { expires: 7, path: '/' });
---
The number of times you visited this page: {counter}

In this example, a cookie named counter is created and the number of page visits is stored. If a cookie named counter already exists, the value of this cookie is updated.

More Information

For more information, you can refer to the Astro Cookie documentation.