Creating a Cloudflare Worker to force custom User-Agent

Hi,

How can I create a Cloudflare Worker that forces a custom user agent when accessing a website?
I would like to force a desktop user agent when accessing a link from my android phone

Yes, it is possible to force the User-Agent from the worker to the origin.

Note that this new User-Agent will not be sent to the client’s browser, but if you have any conditional server-side rendering base on the device type you’ll notice the changes.

const userAgent = 'Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36'

addEventListener('fetch', event => {
    event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
	
	const {request} = event
	
	return await fetch(request.url, {
		...request,
		headers: {
			...request.headers, 
			'User-Agent': userAgent
		}
	})
}

1 Like

Thanks for the reply! Is it possible to force the new user-agent to be sent to the client’s browser?

You can modify the Request Headers from the worker to the origin → , but not the original Request Headers from the worker ← back to the client.