forked from funneltechie/CloudflareWorker-404page
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghl404
36 lines (28 loc) · 879 Bytes
/
ghl404
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
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function fetchAndStreamNotFoundPage(resp) {
const { status, statusText } = resp;
const { readable, writable } = new TransformStream();
const response = await fetch("https://yourwebsite.com/404");
const { headers } = response;
response.body.pipeTo(writable);
return new Response(readable, {
status,
statusText,
headers
});
}
function isHTMLContentTypeAccepted(request) {
const acceptHeader = request.headers.get("Accept");
return (
typeof acceptHeader === "string" && acceptHeader.indexOf("text/html") >= 0
);
}
async function handleRequest(request) {
const response = await fetch(request);
if (response.status === 404 && isHTMLContentTypeAccepted(request)) {
return fetchAndStreamNotFoundPage(response);
}
return response;
}