Last active
October 9, 2020 14:32
-
-
Save jamesbibby/eb99c8ead761b1f3b70762b6cbf27793 to your computer and use it in GitHub Desktop.
SPA Router Cloudflare Worker
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
const ASSET_PATHS = [ | |
'/asset-manifest.json', | |
'/favicon.ico', | |
'/manifest.json', | |
'/precache-manifest.', | |
'/serviceWorker.js', | |
'/static/' | |
]; | |
const S3_BUCKET = "bibs-hello-world-react"; | |
// the SPA request router | |
async function handleRequest(request) { | |
// lets parse the URL into a proper URL object | |
const url = new URL(request.url); | |
// if this is not an asset, return index.html | |
const path = ASSET_PATHS.some((path) => (url.pathname.startsWith(path))) ? | |
url.pathname : '/index.html'; | |
// fetch the path from S3, include the original request | |
// so that headers, auth, etc aren't lost | |
return fetch( | |
`http://${S3_BUCKET}.s3.amazonaws.com${path}`, | |
request | |
); | |
} | |
// add an event listener for fetch that calls the handler | |
self.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