QR code as a data URL with qrcode
toDataURL returns the QR code as a data URL string. You can put it in an img tag, a CSS background or send it to a server.
All qrcode (JavaScript) examples qrcode (JavaScript): usage and stats
How it works
- Await the data URL. Without a callback,
QRCode.toDataURL(text)returns a promise, sogenerateQRcanawaitit insidetry/catch. [1] - Show it as an image. The data URL is set as the
srcof animgelement. The side panel prints the start of the string, its length and its image type. [1] - Callbacks still work. The same function also accepts a callback as its last argument, as in the README's Node.js example. This example uses the promise form instead. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import QRCode from 'qrcode'
const root = document.getElementById('root')
root.style.cssText = 'display:flex;align-items:center;justify-content:center;gap:24px;height:100%;font:14px system-ui,sans-serif;color:#e5e7eb'
// Small helper to create an element with inline styles and text
const el = (tag, css, text) => Object.assign(document.createElement(tag), { style: css || '', textContent: text || '' })
const img = el('img', 'width:200px;height:200px;image-rendering:pixelated;border-radius:8px;background:#fff')
const side = el('div', 'display:grid;gap:8px;width:280px')
const out = el('code', 'word-break:break-all;font-size:12px;color:#a5b4fc')
const size = el('div', 'color:#9ca3af')
side.append(el('b', '', 'toDataURL result'), out, size)
root.append(img, side)
// Promise / async-await form of the API: no callback needed
const generateQR = async text => {
try {
const url = await QRCode.toDataURL(text)
img.src = url // a data URL works anywhere an image URL does
out.textContent = url.slice(0, 90) + '...'
size.textContent = url.length + ' characters, ' + url.slice(5, url.indexOf(';'))
} catch (err) {
console.error(err)
}
}
generateQR('I am a pony!')
Change the text passed to generateQR and run it again to get a new image and data URL. Code written by AgentGid [1].
Change the text passed to generateQR and run it again to get a new image and data URL. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with qrcode 1.5.4. Needs WebGL.
More qrcode (JavaScript) examples
Drawing a QR code on a canvas with qrcode Error correction levels in qrcode Setting the QR code version in qrcode Encoding modes and segments in qrcode
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.