Cloudflare Worker HELP

I have been scratching my head for almost 4 hours but can’t get it to work.

How to redirect and set the header and set nocache at the same time?

I’ve been using something like this but failed

response = new Response()
response.headers.set(‘header1’, ‘value1’)
response.headers.set(‘Cache-Control’, ‘max-age=0’)
response.redirect(‘https://mobile.example.com’)
return response

Response.redirect() returns a new response object, which you are immediately discarding however.

I’d expect the following to work. Probably “work”, as untested :smile:

response = response.redirect('https://mobile.example.com');
response.headers.set('header1', 'value1');
response.headers.set('Cache-Control', 'max-age=0');
return response;

still doesnt work. show 500 error :frowning:

What does the debugger say?

Seems the headers are immutable in that case.

You probably have to construct your own Response object and set the 302 code and the Location header manually.

Something like this?

response = new Response() //construct response object
response.headers.set(‘header1’, ‘value1’);
response.headers.set(‘Cache-Control’, ‘max-age=0’);
response.redirect(‘https://mobile.example.com’);

doesnt work

No, thats the same code you posted already. You have to omit the redirect call and set the status code and the location header manually yourself.

or is there any simple solution for only redirect and set cloudflare to no-cache (no need to set header)?

Try

const resp = new Response(null, { status: 302 });
resp.headers.set('header1', 'value1');
resp.headers.set('Cache-Control', 'max-age=0');
resp.headers.set('Location', 'http://example.com');
return resp;
2 Likes

this is not possible either.
myHeaders .set( name , value ); //needs 2 params

redirect header only have 1 param ```
“HTTP/1.1 301 Moved Permanently”

T[quote=“sandro, post:9, topic:121864”]
Try
[/quote]

This works. Thank you soooo much!!! :smiley:

Worth noting that cache-control doesn’t matter to the browser for redirects; it will only cache a redirect when it has status 301, if it’s 302 it’ll always go to the server before redirecting (won’t use cache).

2 Likes