How to Generate an SVG File in Node.js?

Create SVG graphics in Node.js using xmldom and rough.js. Great for backend data visualization, icons or file-based SVG creation.

Problem

You need to generate SVG files server-side in Node.js, perfect for data visualizations, icon generation or automated graphics. Front-end APIs aren’t an option so you need a pure Node.js solution.

Solution

Use rough.js with xmldom to create SVG in Node. Here’s an example:
const { DOMImplementation, XMLSerializer } = require('xmldom');const rough = require('roughjs'); const fs = require('fs'); const doc = new DOMImplementation().createDocument(null, null); const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); const rc = rough.svg(svg); svg.appendChild(rc.rectangle(10, 10, 200, 100, { fill: 'blue' }); const xml = new XMLSerializer().serializeToString(svg); fs.writeFileSync('output.svg', xml, 'utf-8'); console.log('SVG saved as output.svg');
This creates a simple SVG rectangle and writes it to a file using XML serialization. It works without browser DOM APIs and is good for output or file based graphics.
Also Read: A Comprehensive Guide To Building A Node JS MVC Application

Conclusion

So there you have it! By using xmldom and rough.js you can create and save SVG files in pure Node.js, no headless browser required. This is great for graphics generation and automation workflows.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025