forked from cloudflare/templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (75 loc) · 2.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { getAssetFromKV, mapRequestToAsset } 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 => {
event.respondWith(handleEvent(event));
});
/**
* @param {FetchEvent} event
* @returns {Promise<Response>}
*/
async function handleEvent(event) {
let options = {};
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
};
}
const page = await getAssetFromKV(event, options);
// allow headers to be altered
const response = new Response(page.body, page);
response.headers.set('X-XSS-Protection', '1; mode=block');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('Referrer-Policy', 'unsafe-url');
response.headers.set('Feature-Policy', 'none');
return response;
} 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 });
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
* @param {string} prefix
* @returns {(request: Request) => Request}
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request);
let url = new URL(defaultAssetKey.url);
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/');
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey);
};
}