Skip to content

Commit

Permalink
Handle CF Page build errors (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlgo11 authored Jul 29, 2024
1 parent 463dc17 commit b96ff62
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 10 deletions.
36 changes: 26 additions & 10 deletions functions/redirect.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
export async function onRequest({env, request}) {
const base = env.base || 'https://2fa.pages.dev/'
const country = request.cf?.country.toLowerCase() || "int";
let uri = `${base}${country}`
const res = await fetch(uri, {
cf: {
cacheTtl: 86400, cacheEverything: true
export async function onRequestGet({request}) {
const url = new URL(request.url);
const base = `${url.protocol}//${url.hostname}/`;
const redirectStatus = 302;
try {
const country = request.cf?.country?.toLowerCase() || 'int';
let uri = `${base}${country}/`;

const res = await fetch(uri, {
cf: {
cacheTtlByStatus: {
'200': 60 * 60 * 24 * 7, // Cache request 1 week
'404': 60 * 60 * 24, // Cache request 1 day
},
},
});

// Redirect to /int/ if that page works
if (res.status !== 200) {
const int = await fetch(`${base}int/`);
uri = int.status === 200 ? `${base}/int/`:`${base}/503/`;
}
})
if (res.status !== 200) uri = `${base}/int`

return Response.redirect(uri, 302);
return Response.redirect(uri, redirectStatus);
} catch (e) {
console.error(e);
return Response.redirect(`${base}/502/`, redirectStatus);
}
}
20 changes: 20 additions & 0 deletions layouts/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{{ define "main" }}
<main>
<h1 class="display-1">404</h1>
<p class="note">Not Found</p>
</main>
<style>
main {
display: grid;
justify-content: center;
align-content: center;
height: 100%;
width: 100%;
text-align: center;
}

.note {
font-size: 2em;
}
</style>
{{ end }}
20 changes: 20 additions & 0 deletions layouts/502.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{{ define "main" }}
<main>
<h1 class="display-1">502</h1>
<p class="note">Bad Gateway</p>
</main>
<style>
main {
display: grid;
justify-content: center;
align-content: center;
height: 100%;
width: 100%;
text-align: center;
}

.note {
font-size: 2em;
}
</style>
{{ end }}
20 changes: 20 additions & 0 deletions layouts/503.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{{ define "main" }}
<main>
<h1 class="display-1">503</h1>
<p class="note">Service Unavailable</p>
</main>
<style>
main {
display: grid;
justify-content: center;
align-content: center;
height: 100%;
width: 100%;
text-align: center;
}

.note {
font-size: 2em;
}
</style>
{{ end }}

0 comments on commit b96ff62

Please sign in to comment.