Skip to content

The Rules Snippet example "override a Set-Cookie header with a certain value" uses less reliable cookie parsing #23269

@quantumfusion

Description

@quantumfusion

Existing documentation URL(s)

https://developers.cloudflare.com/rules/snippets/examples/override-set-cookies-value/

What changes are you suggesting?

In using this example, ran into an issue with the way the Set-Cookie response header was being parsed, where it would sometimes drop a cookie and therefore lead to unexpected results.

The example snippet uses its own regex to parse out the cookie:

// Create a new Headers object to modify response headers
const newHeaders = new Headers(response.headers);

// Get all Set-Cookie headers
const cookies = response.headers.get("Set-Cookie");
if (cookies) {
  // Split the Set-Cookie headers
  const cookieArray = cookies.split(/,(?=\s*[^;]+=[^;]+)/g);
  const updatedCookies = cookieArray.map((cookie) => {
...

Instead, we can get the cookieArray directly from the newHeaders object using getSetCookie() https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie, which simplifies down to

const newHeaders = new Headers(response.headers);
const cookies = response.getSetCookie();
if (cookieArray) {
  const updatedCookies = cookieArray.map((cookie) -> {...})
...

Additional information

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions