Skip to content

Instantly share code, notes, and snippets.

@ideabrian
Forked from longseespace/worker.js
Created September 15, 2024 04:01
Show Gist options
  • Save ideabrian/82ecc5414c782a353491d784a17d706b to your computer and use it in GitHub Desktop.
Save ideabrian/82ecc5414c782a353491d784a17d706b to your computer and use it in GitHub Desktop.
Cloudflare Worker Proxy
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const { pathname, search } = url;
var newPathname = pathname;
if (pathname.startsWith('/docs')) {
newPathname = pathname.replace('/docs', '');
}
const originUrl = `https://docs.boltai.com${newPathname}${search}`;
console.log('originUrl', originUrl);
const fetchOptions = {
method: request.method,
headers: request.headers,
redirect: 'follow', // Ensure redirects are followed
};
const response = await fetch(originUrl, fetchOptions);
// Check if the response is HTML
const contentType = response.headers.get('content-type');
if (contentType && (contentType.includes('text/html') || (contentType.includes('text/css')))) {
// Get the response text
let text = await response.text();
// Replace the script sources
text = text.replace(
/\/_next\/static/g,
'https://boltai.com/docs/_next/static'
);
// Replace the canonical link
text = text.replace(
/<link rel="canonical" href="https:\/\/docs\.boltai\.com\/docs/g,
'<link rel="canonical" href="https://boltai.com/docs'
);
// Create a new response with the modified HTML
const newResponse = new Response(text, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
return newResponse;
}
// If not HTML, return the original response
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment