How to use Webflow to host parts of your site (Cloudflare Workers)

A workaround to Webflow’s hosting limitations + CMS sub-category routing with wildcard paths.

Getting Started

addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
console.log(‘Got request’, request)
const response = await fetch(request)
console.log(‘Got response’, response)
return response
}
async function handleRequest(request) {  //1. Parse the URL to get some useful info
let parsedUrl = new URL(request.url)
let pathStripped = parsedUrl.pathname.replace(/^(.+?)\/*?$/, “$1”)
//2. Webflow URL to forward your pages to
var forwardHost = “https://proxy.example.com"
//3. Paths you’d like to match and forward
var urlPatterns = [“/”, “/about”]
//4. Match the routes, and forward the request
if (urlPatterns.indexOf(pathStripped) > -1) {
return await fetch(forwardHost + parsedUrl.pathname, request)
}
//5. Return deafult response
const response = await fetch(request)
return response
}

Wildcard Routing

function convertToRegexString(pattern) {

//Escape Regex expression
pattern = pattern.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
//Build Regex string
return "^" + pattern.replace(/\\\*/g, '.*').replace(/\\\?/g, '.') + "$"
}
//4. Match the routes, and forward the request
if (urlPatterns.some(pattern => (new RegExp(convertToRegexString(pattern))).test(pathStripped))) {
return await fetch(forwardHost + parsedUrl.pathname, request)
}
//3. Paths you’d like to match and forward
var urlPatterns = ["/blog/*"]

Bonus Tip 1: Routing to different path

//3. Paths you’d like to match and forward
var urlPatterns = ["/home", ["/about", "/about-us"]]
//4. Match the routes, and forward the request
for (var i = 0; i < urlPatterns.length; i++) {
//4.1 Get the pattern, check for array
var pattern = urlPatterns[i]
var forwardPath = parsedUrl.pathname
if (Array.isArray(pattern)) {
forwardPath = pattern[1]
pattern = pattern[0]
}

//4.2 Check for a match
if ((new RegExp(convertToRegexString(pattern))).test(pathStripped)) {
return await fetch(forwardHost + forwardPath, request)
}
}

Bonus Tip 2: CMS sub-category routing

//4.2 Check for a match
if ((new RegExp(convertToRegexString(pattern))).test(pathStripped)) {
var parts = pathStripped.split('/');
var ending = forwardPath.substr(-1) == '/' ? parts[parts.length - 1] : ""
return await fetch(forwardHost + forwardPath + ending, request)
}
//3. Paths you’d like to match and forward
var urlPatterns = [["/blog/category/*", "/blog-categories/"]]