qr-svg is a small JavaScript library that returns a QR code as an SVG string: one <rect> for the background and one <path> for the modules, on integer coordinates with shape-rendering="crispEdges". It stays sharp at any size, prints cleanly and renders under a strict Content Security Policy. Zero dependencies, 4.0 KB gzipped, one call in Node or in the browser — so a QR code at build time in Node is the same markup as one drawn in a page.
Why an SVG string
- Small output. A run of dark modules in a row is one subpath, so the QR of a short URL is about 2.5 KB of markup: no groups, masks, filters,
<use>or one element per module. - Renders under a strict CSP. No
style="", no<style>, no<script>, nodata:orurl(): colours are presentation attributes, checked against an allowlist (hex,rgb(),hsl(), a keyword) before they are written. A QR code under a strict CSP needs nothing extra. - Scales to its container. Without a
sizethe SVG has only aviewBox; with one it getswidthandheightin pixels. The drawing is the same either way.
How to use it
Install from npm with npm install @spintax/qr-svg, then:
const svg = QR.renderSvg(QR.generateMatrix('https://example.com'));
It is one UMD file: a default import, require(), or a <script> from a CDN that defines the global QrSvg. The live demo lets you type text, pick a level, colours and a size, then copy or download the SVG.
API
generateMatrix(text, options)encodes the text into a matrix of modules: error correction levels L, M, Q and H (default M), versions 1 to 40, numeric, alphanumeric and UTF-8 byte modes, an automatic or forced mask, and optionalboostEcc.renderSvg(matrix, options)draws it:quiet(the margin, 4 modules by default),size,fgandbg('transparent'works). A colour that is not a plain colour value throws, because it lands inside an attribute.buildPathData(matrix, quiet)returns thedattribute alone, for a caller that builds its own element — in a browser extension, say.
Accuracy and stability
It is a QR encoder without dependencies: a port of uqr and Project Nayuki's generator (ISO/IEC 18004) that draws the same matrix module for module — a test compares the two over every version. The tests also decode what is drawn with an independent reader, jsQR, at several scales and every mask. Within a minor version the same text and options give a byte-identical SVG.
Licence
MIT. Built by 301; the encoder's original notices (uqr, Project Nayuki) ship in the LICENSE file.