Send Headers to Origin


#1

It is possible that Cloudflare sends a Header for example called “mobile” with yes / no. To show different content if the client is from a phone or PC? We have already resolved with the user-agent to detect the device, but we can not send this information to the “Origin”.

Cloufront (Amazon) has a Header called “CloudFront-Is-Mobile-Viewer” that allows you to make two different cache copies according to the device.

Is there a similar function in Cloudflare?


#2

Yes, you can easily do this with workers.

Here is an example that can get you started (eg. you may want to adjust the detection to your own implementation):


#3

Hello Martin !

We have almost solved the problem, we see that we could pass the Header to the origin without problem, but Cloudflare continues to show the same content, how do you think Cluodflare could show two versions of the same URL based on the Header that is sent?

We made an attempt with the modifications that were important, but it did not work.
Thank you very much for your help !

addEventListener(‘fetch’, event => {
event.respondWith(fetchAndApply(event.request))
})

function isMobile(userAgent) {
return userAgent.match(/iPhone|Android|Mobile|mobile|webOS/i) ? ‘true’ : ‘false’;
}

async function fetchAndApply(request) {
let isMobileResult = isMobile(request.headers.get(‘user-agent’))

request = new Request(request)
request.headers.set(“IS-MOBILE”, isMobileResult)

let headers = {
‘IS-MOBILE’: isMobileResult
}
const init = {
headers: headers
}

const response = await fetch(request, init)

return response
}


#4

From your first post I was under the impression you wanted to do caching on your origin server, and let the origin server decide which version to serve.

If you want Cloudflare to cache the html requests for you (with cache everything enabled), you can do one of the following:

  • use Custom Cache Keys (Enterprise plan only)
  • serve the mobile content from a different URL, and use the worker to rewrite/proxy to that URL based on device.