Skip to content

Commit 20feb93

Browse files
RealOrangeOnehelenb
authored andcommitted
Include torchbox-mode cookie in cache key
1 parent dd4654d commit 20feb93

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

cloudflare/workers.js

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,14 @@ function getCachingRequest(request) {
137137
*
138138
* Note: Modifications to this request are not sent upstream.
139139
*/
140-
return new Request(new URL(request.url), request); // Do nothing.
140+
const cookies = getCookies(request);
141+
142+
const requestURL = new URL(request.url);
143+
144+
// Cache based on the mode
145+
requestURL.searchParams.set('cookie-torchbox-mode', cookies['torchbox-mode'] || 'dark');
146+
147+
return new Request(requestURL, request);
141148
}
142149

143150

@@ -187,13 +194,30 @@ function hasPrivateCookie(request) {
187194
return false;
188195
}
189196

190-
const requestCookieNames = cookieHeader
191-
.split(";")
192-
.map((cookie) => cookie.split("=")[0].trim());
197+
const allCookies = getCookies(request);
193198

194-
return PRIVATE_COOKIES.some((privateCookieName) =>
195-
requestCookieNames.includes(privateCookieName)
196-
);
199+
// Check if any of the private cookies are present and have a non-empty value
200+
for (const cookieName of PRIVATE_COOKIES) {
201+
if (cookieName in allCookies && allCookies[cookieName]) {
202+
return true;
203+
}
204+
}
205+
return false;
206+
}
207+
208+
function getCookies(request) {
209+
/*
210+
* Extract the cookies from a given request
211+
*/
212+
const cookieHeader = request.headers.get('Cookie');
213+
if (!cookieHeader) {
214+
return {};
215+
}
216+
217+
return cookieHeader.split(';').reduce((cookieMap, cookieString) => {
218+
const [cookieKey, cookieValue] = cookieString.split('=');
219+
return { ...cookieMap, [cookieKey.trim()]: cookieValue.trim() };
220+
}, {});
197221
}
198222

199223
/**

0 commit comments

Comments
 (0)