Return HTML Response and Add Cookie - Cloudflare Worker

Viewed 30

I am attempting to return a response header of 'Set-Cookie', while also return a new HTML response by editing CSS. In other words, I am seeking a way to perform both of these actions in one instance (or merge my two IF statements into one):

  const country = request.cf.country
  let cookies = request.headers.get('Cookie') || ""
  const url = new URL(request.url)
  let response = await fetch(request);
  response = new Response(response.body, response);

    if (country != 'US' && country !='CA') {
response.headers.set('Set-Cookie', "new-int-pricing-mode=on;max-age=604800;Path=/");
return response;
}


if (country != 'US' && country !='CA') 
{const response = await fetch(request)

    var html = await response.text()
    
    // Inject scripts
    const customScripts = '<style type="text/css">STYLING HERE</style></body>'
    html = html.replace( /<\/body>/ , customScripts)
    
    // return modified response
       return new Response(html, response)

}

Because I am returning a new Response in one, and only "response" in another - so far all of my "merge" techniques are failing. Is this possible?

I have managed to 99% merge through the use of the cookies. But on first page load, the styling will not take effect (due to the need to apply the cookie)

    if ((country != 'US' && country !='CA') && !(cookies.includes("pricing-mode=on"))) {
response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");
return response;
}

    else if ((country != 'US' && country !='CA') && (cookies.includes("pricing-mode=on"))) {

    const response = await fetch(request)

    var html = await response.text()
    
    // Inject scripts
    const customScripts = '<style type="text/css">STYLE HERE</style></body>'
    html = html.replace( /<\/body>/ , customScripts)
    
    // return modified response
       return new Response(html, response)

}
1 Answers

You can create a new response object. https://developers.cloudflare.com/workers/examples/modify-response/

  const originalResponse = await fetch(request);

  // Change status and statusText, but preserve body and headers
  let response = new Response(originalResponse.body, {
    status: 500,
    statusText: 'some message',
    headers: originalResponse.headers,
  });

You can add headers to this response using response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");

Related