How to return an SVG source from a CloudFlare Worker

Posted on December 10, 2022

If you want to return an SVG generated source from a CloudfFlare Worker call, here the code:

async function handleRequest (request) {
  const svg = `<svg 
    viewBox="0 0 500 300">
      <circle r="50" cx="250" cy="150"></circle>

  return new Response(svg, { headers: { 'content-type': 'image/svg+xml' } })

addEventListener('fetch', event => {

The above code, published as CloudFlare Worker will return a simple circle in a SVG file.

In case you'd like to experiment with chart generation within a Worker, take a look the source code of this tiny project I did a while ago that generates little spark charts as SVG just passing some parameters.