Conditional redirection through workers

Hey!

I have a site that serves different content to users in the U.S. and users in the rest of the world. This works through a ?lang=can query string. My goal is to ensure all users go to the correct version of the site – if a U.S. user goes to Example Domain, then they’re redirected to example.com. If a Canadian user goes to example.com, then they’re redirected to Example Domain.

I set up a Cloudflare worker, but I keep getting recursive loops and I’m not sure how to avoid the fetch function from being invoked multiple times.

Here’s my code:

export default {

	async fetch( req ) {
		if ( 'GET' !== req.method ) {
			return fetch( new Request( req.url, req ) )
		}

		const urlTargetObj = new URL( req.url )

		if ( 'US' !== req.cf.country ) {
			urlTargetObj.searchParams.set( 'lang', 'can' )
		} else {
			urlTargetObj.searchParams.delete( 'lang' )
		}

		const urlTarget = urlTargetObj.toString()

		if ( urlTarget === req.url ) {
			return fetch( req.url )
		} else {
			return Response.redirect( urlTarget, 301 )
		}
	},

}

I tried using Country code redirect · Cloudflare Workers docs as an example, but the same thing happens in this example – if the user’s country code is not US or EU, then they hit the return fetch( request ) and gets stuck in a recursive loop.

If this isn’t feasible, is there another way to add/remove a query param based on a user’s country code?

Thanks!