Created
May 5, 2023 18:30
-
-
Save philipproth/3b6f24723f4acc8af3d9c6c73120c63a 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
const PRERENDER_TOKEN = 'your_prerender_token'; | |
const PRERENDER_URL = 'https://service.prerender.io/'; | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
if (shouldPrerender(request)) { | |
const prerenderUrl = PRERENDER_URL + url.href + '?token=' + PRERENDER_TOKEN; | |
const prerenderResponse = await fetch(prerenderUrl); | |
return new Response(prerenderResponse.body, { | |
status: prerenderResponse.status, | |
statusText: prerenderResponse.statusText, | |
headers: prerenderResponse.headers, | |
}); | |
} else { | |
return fetch(request); | |
} | |
} | |
function shouldPrerender(request) { | |
const userAgent = request.headers.get('User-Agent') || ''; | |
const isCrawler = /bot|googlebot|crawler|spider|robot|crawling/i.test(userAgent); | |
return isCrawler; | |
} | |
addEventListener('fetch', (event) => { | |
event.respondWith(handleRequest(event.request)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment