- main
- manifest
- deps
- main
- Install
- Run
import { getGeolocationForIpAddress } from "fastly:geolocation";
import { HTMLRewritingStream } from "fastly:html-rewriter";
async function handleRequest(event) {
try {
const clientIp = event.client.address;
const geo = getGeolocationForIpAddress(clientIp);
const city = geo?.city || "The Matrix";
const country = geo?.country_name || "Cyberspace";
const backendResponse = await fetch("https://example.com", {
backend: "example"
});
const transformer = new HTMLRewritingStream()
.onElement("head", (el) => {
el.append(`
<style>
body {
font-family: 'Comic Sans MS', 'Chalkboard SE', cursive !important;
background: linear-gradient(45deg, #ff00ff, #00ffff) !important;
color: #0000ff !important;
}
h1, h2, h3 {
color: #ffff00 !important;
background-color: #000000 !important;
padding: 10px;
text-align: center;
border: 4px dashed #ff0000;
text-transform: uppercase;
}
</style>
`, { escapeHTML: false });
})
.onElement("head", (el) => {
el.prepend(`<base href="https://example.com/">`, { escapeHTML: false });
})
.onElement("body", (el) => {
el.prepend(`
<marquee scrollamount="12" style="background: #000; color: #00ff00; font-family: monospace; font-size: 22px; padding: 12px; border-bottom: 5px solid #ff00ff; display: block;">
⚡ WELCOME SURFER! ⚡ REWRITING LIVE AT THE EDGE FOR A VISITOR IN ${city.toUpperCase()}, ${country.toUpperCase()}! YOU ARE THE 1,000,000th VISITOR! ⚡
</marquee>
`, { escapeHTML: false });
})
.onElement("h1", (el) => {
el.append(" 🔥 FASTLY COMPUTE HTMLREWRITINGSTREAM ACTIVE 🔥");
});
const rewrittenBody = backendResponse.body.pipeThrough(transformer);
return new Response(rewrittenBody, {
status: 200,
headers: new Headers({
"content-type": "text/html; charset=utf-8",
}),
});
} catch (error) {
console.error(error);
return new Response("Internal Server Error", { status: 500 });
}
}
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));