Setting Cookies

Last updated: 2024-04-18 09:47:31
In this example, cookies are used to count the number of access requests. When a browser accesses the Edge Functions service, the number of access requests is increased by 1.

Sample code

async function handleRequest(request) {
// Retrieve the cookies from the current request
const cookies = request.getCookies();
const cookieCount = cookies.get('count');
// Increment the count
const count = Number(cookieCount && cookieCount.value || 0) + 1;
// Update the count in the cookie
cookies.set('count', String(count));

const response = new Response(The count is: ${count});
// Set the response cookies
response.setCookies(cookies);
return response;
}

addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});

Sample Preview

In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of the sample code.


References