69 lines
1.7 KiB
JavaScript
69 lines
1.7 KiB
JavaScript
import { getAssetFromKV } 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 = {
|
|
cacheControl: {
|
|
browserTTL: 3600,
|
|
}
|
|
}
|
|
|
|
let headers = {
|
|
'X-XSS-Protection': '1; mode=block',
|
|
'X-Frame-Options': 'DENY',
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'x-y2k-backend': 'v5',
|
|
'x-y2k-debug': DEBUG,
|
|
}
|
|
|
|
try {
|
|
if (DEBUG) options.cacheControl.bypassCache = true
|
|
|
|
// asset was found, the good stuff goes here
|
|
let asset = await getAssetFromKV(event, options)
|
|
|
|
// set various security headers above
|
|
Object.keys(headers).forEach((name) => {
|
|
asset.headers.set(name, headers[name])
|
|
})
|
|
|
|
return asset
|
|
} 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(), { headers, status: 500 })
|
|
}
|
|
}
|