Worker reverse proxy not following redirects

I have a simple reverse proxy - it’s working great apart from at certain times (and this is by design) the origin will return a redirect. The redirected content is being served on the proxied url (this is not desirable).

const DOMAIN = 'www.public.com';   
const PROXYPATH = 'docs';
const ORIGIN = 'www.private.com';

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/' + PROXYPATH + '/') || url.pathname === '/' + PROXYPATH) {
    handleRequest(event, url);
  } else {
    event.respondWith(fetch(event.request));
  }
})

async function handleRequest(event, url) {
  // Change URL from public URL to use the origin URL
  var originUrl = url.toString().replace(
      'https://' + DOMAIN + '/' + PROXYPATH, 
      'https://' + ORIGIN
    );
    event.passThroughOnException();
    event.respondWith(fetch(originUrl));
}

So lets say ORIGIN www.private .com/docs is responding with a 302 to www. anothersite .com, the www.anothersite .com body would be there with www.public .com/docs in the browser url.

What I would like to happen is when the origin is responding with a redirect then the redirect happens in the users browser, i.e. it goes to www.anothersite .com.

(spaces added to get around link limit)

hello @neil3, instead of fetching the content from originUrl you should do a Response.redirect instead.

Easiest option (exposing your origin domain):

return Response.redirect(originUrl, 301)

The recommended option (catching the redirect URL from your or origin domain without exposing your it)

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

const PROXYPATH = 'docs'
const DOMAIN = 'www.public.com'
const ORIGIN = 'www.private.com'

async function handleRequest(request) {
	
	const url = new URL(request.url)
	const {pathname} = url
	
	if(pathname.startsWith('/' + PROXYPATH + '/') || pathname === '/' + PROXYPATH)
	{
		const originUrl = url.toString().replace(
			'https://' + DOMAIN + '/' + PROXYPATH, 
			'https://' + ORIGIN
		);
		
		const response = await fetch(originUrl)
		
		if(response.ok)
		{
			if(response.url !== originUrl)
			{
				return Response.redirect(response.url, 301)
			}
		}		
	}
	
	return fetch(request) // or return response, depending on what you want to achieve 
}