Skip to content

Instantly share code, notes, and snippets.

@jamesbibby
Last active October 9, 2020 14:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbibby/eb99c8ead761b1f3b70762b6cbf27793 to your computer and use it in GitHub Desktop.
Save jamesbibby/eb99c8ead761b1f3b70762b6cbf27793 to your computer and use it in GitHub Desktop.
SPA Router Cloudflare Worker
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