-
-
Save simevidas/d8ec51a51b05d4fabee6ddbe90c938ce to your computer and use it in GitHub Desktop.
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
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 }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ty sir!