Embedding a raw gif directly within Cloudflare Worker?

Is it possible to embed a small gif image directly in a standard Cloudflare Worker? Attempting to do so using the web editor, without using wrangler. I’m using a Cloudflare Worker as a pixel tracker relay for increased performance. The end of the response is to return a 1x1 pixel image like this:

async function handleRequest( request ) {
  return fetch( "https://random-public-domain.tld/empty.gif" )
}

I was wondering if I could save myself a subrequest by just returning the file directly. I tried to base64 encode the file content then decode within the response however that doesn’t seem to preserve the raw file contents as the gif file is corrupt.

async function handleRequest( request ) {
  base64 = "R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
  return new Response( atob(base64), { status: 200, headers: { "content-type": "image/gif" } } )
}

Try the following:

async function handleRequest( request ) {
  const base64 = "R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
  return new Response( Uint8Array.from(atob(base64), c => c.charCodeAt(0)), { status: 200, headers: { "content-type": "image/gif" } } )
}

(Credit to @sandro)

3 Likes

Amazing, it works! Thank you.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.