Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/6e252457754506e949619ddb17a9ca4b to your computer and use it in GitHub Desktop.
Save rstacruz/6e252457754506e949619ddb17a9ca4b to your computer and use it in GitHub Desktop.

Cloudflare worker example

This worker modifies the response HTML.

addEventListener('fetch', event => {
let response = handleRequest(event.request)
event.respondWith(response)
})
async function handleRequest(request) {
const url = new URL(request.url)
// Proxy devhints.io => my-other-website.netlify.app
// and inject some markup
if (url.host === 'devhints.io') {
url.host = 'my-other-website.netlify.app'
let res = await fetch(url.toString(), request)
res = await injectMarkup(request, res)
return res
}
}
async function injectMarkup(req, res) {
if (!res.ok) return res
// Only process text/html responses
const type = res.headers.get('content-type')
if (!type.match(/^text\/html/)) return res
// Update the body text
const body = await res.text()
const ip = request.headers.get('cf-connecting-ip')
const html = body.replace(
'<html ',
`<html data-connecting-ip="${ip}" `
)
return new Response(html, res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment