Skip to content

Instantly share code, notes, and snippets.

@philipproth
Created May 5, 2023 18:30
Show Gist options
  • Save philipproth/3b6f24723f4acc8af3d9c6c73120c63a to your computer and use it in GitHub Desktop.
Save philipproth/3b6f24723f4acc8af3d9c6c73120c63a to your computer and use it in GitHub Desktop.
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