Skip to content

Instantly share code, notes, and snippets.

Created October 17, 2022 10:46
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Prerender New Worker
// User agents handled by Prerender
const BOT_AGENTS = [
"yahoo! slurp",
"quora link preview",
"google page speed",
"bitrix link preview",
"integration-test", // Integration testing
// These are the extensions that the worker will skip prerendering
// even if any other conditions pass.
export default {
* Hooks into the request, and changes origin if needed
async fetch(request, env) {
return await handleRequest(request, env).catch(
(err) => new Response(err.stack, { status: 500 })
* @param {Request} request
* @param {any} env
* @returns {Promise<Response>}
async function handleRequest(request, env) {
const url = new URL(request.url);
const userAgent = request.headers.get("User-Agent")?.toLowerCase() || "";
const isPrerender = request.headers.get("X-Prerender");
const pathName = url.pathname.toLowerCase();
const extension = pathName
.substring(pathName.lastIndexOf(".") || pathName.length)
// Prerender loop protection
// Non robot user agent
// Ignore extensions
if (
isPrerender ||
!BOT_AGENTS.some((bot) => userAgent.includes(bot)) ||
(extension.length && IGNORE_EXTENSIONS.includes(extension))
) {
return fetch(request);
// Build Prerender request
const newURL = `${request.url}`;
const newHeaders = new Headers(request.headers);
newHeaders.set("X-Prerender-Token", env.PRERENDER_TOKEN);
return fetch(new Request(newURL, {
headers: newHeaders,
redirect: "manual",
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment