Skip to content

Instantly share code, notes, and snippets.

@simevidas
Created January 5, 2021 05:55
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simevidas/d8ec51a51b05d4fabee6ddbe90c938ce to your computer and use it in GitHub Desktop.
Save simevidas/d8ec51a51b05d4fabee6ddbe90c938ce to your computer and use it in GitHub Desktop.
import {
getAssetFromKV,
serveSinglePageApp,
} from '@cloudflare/kv-asset-handler';
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false;
addEventListener('fetch', (event) => {
try {
event.respondWith(handleEvent(event));
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
})
);
}
event.respondWith(new Response('Internal Error', { status: 500 }));
}
});
async function handleEvent(event) {
let options = { mapRequestToAsset: serveSinglePageApp };
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
};
}
return await getAssetFromKV(event, options);
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: (req) =>
new Request(`${new URL(req.url).origin}/404.html`, req),
});
return new Response(notFoundResponse.body, {
...notFoundResponse,
status: 404,
});
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 });
}
}
@vanjohnson879
Copy link

Yes! Why has this been such a hard thing to find. Thank you for your contribution!

@otherperspectives
Copy link

Thank you for the help!

@wasa4587
Copy link

Thank you

@nicgene
Copy link

nicgene commented Jan 4, 2022

Thanks!

@0xsShady
Copy link

ty sir!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment