HOW TO: Create a downtime failover for your site with a Cloudflare Worker

October 2, 2020

This is a method to route traffic to another site without changing the domain that appears for your visitors if your live site can't be reached or a 50X error is detected.

The logic behind this worker is simple enough. It checks the response code sent to a visitor on a page request. If the origin doesn't respond within 4 seconds OR responds with a 50X error (500, 502, 504, etc..) it will serve the visitor a page from a completely separate site.

I will not be covering how to keep the duplicate "failover" site in sync with production or how to rewrite the on-page links of the second site, though that's coming soon.

The worker

Head to the Workers page in your Cloudflare account, click Create a Worker and then Quick Edit. Add the following snippet into the Script box:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {

// Make a promise to fetch without a condition
let fetchPromise = fetch(request)

// Another promise that ends without definition after 4 seconds
let timeoutPromise = new Promise(resolve => setTimeout(resolve, 4000))

// See which promise wins the race!
let response = await Promise.race([fetchPromise, timeoutPromise])

// If there's a successful response from origin, check the status code
if (response) {

// If the status code is anything numerically above 500, failover!
  if ((response.status >= 500)){
    var failoverURL = new URL(request.url)
    failoverURL.hostname = "failover.domain.com"
    return fetch(failoverURL, request, { cf: { resolveOverride: '403page.com' } })
  }

// If the status code is less than 500, serve from origin
  return response;

// Otherwise, if a timeout occurs, failover!
} else {
      var failoverURL = new URL(request.url)
    failoverURL.hostname = "failover.domain.com"
    return fetch(failoverURL, request, { cf: { resolveOverride: '403page.com' } })
}}

You will need to change both instances of 403page.com to your live domain AND change both instances of failover.domain.com to your failover domain.

Click Save and back right out to the main Cloudflare dashboard for the live domain. Click on the on the Workers tab and then Add Route.

Enter the live domain name including a * at the end (ie. 403page.com*).

Click Save and you're all set!