Proxy another website url on a particular path using cloudflare workers – modify response body

// cloudflare worker to proxy a path or a whole url and make changes in response for any use case. 
const SECOND_DOMAIN = 'second.YOURDOMAIN.com'
const THIRD_DOMAIN = 'third.YOURDOMAIN.com'
const THIRD_PATH = 'abc-pathname-seo'
const THIRD_LINK = 'https://' + THIRD_DOMAIN + THIRD_PATH
async function handleRequest(event) {
    const url = new URL(event.request.url)
    const pathname = url.pathname
    if (pathname === '/' + THIRD_PATH) {
        return thirdLander(event)
    }
    const search = url.search
    const pathWithParams = pathname + search
    return retrieveStatic(event, pathWithParams)
}

async function retrieveStatic(event, pathname) {
    let response = await caches.default.match(event.request)

    if (response) {
        return response
    }

    const requestHeaders = new Headers(event.request.headers)
    const headers = new Headers()

    headers.set('Host', SECOND_DOMAIN)
    headers.set('Accept', requestHeaders.get('Accept'))
    headers.set('Accept-Encoding', requestHeaders.get('Accept-Encoding'))

    let init = {
        redirect: 'manual',
        method: event.request.method,
        headers: headers,
    }

    response = await fetch(`https://${THIRD_DOMAIN}/${pathname}`, init)

    if (event.request.method === 'GET') {
        event.waitUntil(caches.default.put(event.request, response.clone()))
    }

    return response
}
async function thirdLander(event) {
    let response = await caches.default.match(event.request)

    if (response) {
        return response
    }
    const requestHeaders = new Headers(event.request.headers)
    const headers = new Headers()

    headers.set('Host', THIRD_DOMAIN)
    headers.set('Accept', requestHeaders.get('Accept'))
    headers.set('Accept-Encoding', requestHeaders.get('Accept-Encoding'))
    headers.set('Cookie', requestHeaders.get('Cookie'))

    let init = {
        redirect: 'manual',
        method: event.request.method,
        headers: headers,
    }
    response = await fetch(THIRD_LINK, init)
// RESPONSE BODY MODIFICATION
    let res2 = response.clone()
    let orgBody = await response.text()
    orgBody = orgBody.replace(/src="\//g, 'src="')
    orgBody = orgBody.replace(/url\("\//g, `url("https://${THIRD_DOMAIN}/`)
    orgBody = orgBody.replace(/<\/head>/g, `<base href="https://${THIRD_DOMAIN}/" target=_blank><link rel="canonical" href="https://YOURDOMAIN.com${THIRD_PATH}" /></head>`)

    if (event.request.method === 'GET') {
        event.waitUntil(caches.default.put(event.request, new Response(orgBody, res2)))
    }
    return new Response(orgBody, res2)
}
addEventListener("fetch", (event) => {
    event.passThroughOnException()
    event.respondWith(handleRequest(event))
})

Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *