Cookies
This example shows how to read a cookie value from request headers and write a cookie value to response headers.
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const spCookie = getCookieValue(
request.headers.get("cookie"),
"sp-cookie-name"
);
const response = await fetch(request);
// Conditionally add cookie based on presence of sp-cookie-name cookie of request
if (spCookie) {
// Using append to add a set-cookie header to response.
// Use set instead if it is desired to overwrite existing set-cookie headers on response.
response.headers.append(
"set-cookie",
`cookie-name=cookie-value; Domain=.stackpath.com; Path='/';`
);
}
return response;
}
// Taken from https://github.com/pillarjs/cookies/blob/master/index.js#L62
const getCookieValue = (cookies, name) => {
if (!cookies) {
return null;
}
let regex = new RegExp(
"(?:^|;) *" + name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + "=([^;]*)"
);
let match = cookies.match(regex);
if (!match || !match[1]) {
return null;
}
return match[1];
};
Updated 5 months ago
What’s Next