Cloudflare Workers Tutorial Part-4: Proxying, Caching and Custom Error Pages

Some very interesting things in this last part of the Cloudflare Workers Tutorial series. We will see how we can do Proxying, caching, and custom error pages with Cloudflare Workers.

Proxying with Workers

For this section, I will fetch the webpage of my other site h4ck3r.in on techtorrent.org, the site I am using in this tutorial as a playground.

Note that the site techtorrent.org actually doesn’t have anything. The whole response we get will be from Cloudflare Worker fetched from the actual site (h4ck3r.in).

Proxy example
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  // fetch path from the request URL
  let path = new URL(request.url).pathname
  let response = await fetch ('https://h4ck3r.in' + path);

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText
  })
 
}

Caching with Workers

In this section we will see how we can cache page on Cloudflare and skip cache.

We will only cache page cache-me.html for 5 seconds.

We will write a if block for this. If request matches, then store to the cache.

To verify that page is cached there are 2 methods.

  1. Verify header CF-Cache-Status header.
  2. Add something with PHP to the HTML page which keeps updating it. Old content = cached response.

For the sake of simplicity I will be using method 1.

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

async function handleRequest(request) {
    
  if ( request.url.match('cache-me') ) {
    let response = await fetch(request, { cf: { cacheTtl: 5 } })
    response = new Response(response.body, response)
    return response
  } else {
    let response = await fetch(request, { cf: { cacheTtl: 0 } })
    response = new Response(response.body, response)
    return response
  }

}
Cloudflare cache headers

As you can see in above request the cache is 3 seconds old (Age) and content is served from Cloudflare cache (CF-Cache-Status: HIT).

Custom Error Pages

This can be handy if you want to serve custom error pages from the Proxy.

In this example, we will serve a 404 page from Marvel’s website.

Marvel’s 404 page
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  const response = await fetch(request);

  // if the page was not found
  if (response.status === 404 ) {

    const someHTML = `<!DOCTYPE html>
    <html>
      <body>
      <iframe src="https://www.marvel.com/404" style="position:absolute; top:0; left:0; width:100%; height:100%; border:0"></iframe>
      </body>
    </html>
    `

    const init = {
      headers: {
        'content-type': 'text/html;charset=UTF-8',
      },
    }
    return new Response(someHTML, init)
  }

  // otherwise we return the original response
  return response;
}

//https://developers.cloudflare.com/workers/templates/pages/send_raw_html/

This was it for part-4, Proxying, caching, and custom error pages with Cloudflare Workers.

Congratulations! You have completed the tutorial successfully. Let me know your suggestions. I am on Twitter as @dhsathiya and on Instagram as @d.vlpr.

Leave a Reply

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