banjocode Convert a SVG file to PNG and serve it in Express

Convert a SVG file to PNG and serve it in Express

I tend to use SVG:s a lot, however, sometimes I feel like it simpler to render them as PNG:s for some special workflows. This a neat trick to do that in your own API.

2 min read

Rendering SVG to PNG in an API

I work a lot with SVG:s, but sometimes I want to render them as PNG:s to make some of my workflows simpler. This is a neat trick that uses the sharp library within express to generate a PNG file from SVG and serve it in an endpoint.

server.get("/api/cover/:id", function(req, res) {
    var svg = getSvg(req.params.id);
    const buffer = Buffer.from(svg);
    const img = await sharp(buffer).png();

   res.writeHead(200, {
     'Content-Type': 'image/png',
     'Content-Length': img.length
   });

   res.end(img); 
});