Created
January 20, 2021 21:40
-
-
Save louisbarclay/7361401219617c848f751cfd1e0761cd to your computer and use it in GitHub Desktop.
Cloudflare worker script to put Roam Research public graph at custom domain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Config for our domain (where we want the Roam blog to live) | |
// and the start page (where we want our readers to land) | |
// Change these to suit your case! | |
// IMPORTANT: don't have '/' at the end of either domain or startPage | |
const config = { | |
domain: "roam.cloak.ist", | |
startPage: "/#/app/nudge/page/RI01qJl4P", | |
} | |
// Function that processes requests to the domain the worker is at | |
async function handleRequest(request) { | |
// Grab the request URL's pathname, we'll use it later | |
const url = new URL(request.url) | |
const targetPath = url.pathname | |
// Send request through to roamresearch.com, get response | |
let response = await fetch(`https://roamresearch.com${targetPath}`) | |
// For the root path, modify the response to send to startPage | |
if (targetPath === '/') { | |
return modifyResponse(response) | |
} else { | |
// For other paths, simply return the response | |
return response | |
} | |
} | |
// Modify the response for root path | |
async function modifyResponse(response) { | |
return new HTMLRewriter() | |
.on("head", new HeadRewriter()) | |
.transform(response) | |
} | |
// Change the head of the HTML document | |
class HeadRewriter { | |
element(element) { | |
element.prepend( | |
`<script> | |
if (window.location.hash === "" && window.location.host === "${config.domain}") { | |
history.pushState(history.state, "", "${config.startPage}"); | |
} | |
</script>`, | |
{ | |
html: true, | |
} | |
) | |
} | |
} | |
// Listen for requests | |
addEventListener("fetch", (event) => { | |
event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment