Generating data URLs in JavaScript

All data URLs (also known as data URIs) begin with data:, followed by the media type string (which can be omitted) and the data itself.

Below are some examples of data URLs and ways to generate them.


const data = 'Hello World!'


const data = 'Hello World!'
console.log(`data:text/plain;charset=utf-8;base64,${btoa(unescape(encodeURIComponent(data)))}`) // Browser
console.log(`data:text/plain;charset=utf-8;base64,${Buffer.from(data).toString('base64')}`) // Node.js


const data = '<b>Hello World!</b>'
console.log(`data:text/html;charset=utf-8;base64,${btoa(unescape(encodeURIComponent(data)))}`) // Browser
console.log(`data:text/html;charset=utf-8;base64,${Buffer.from(data).toString('base64')}`) // Node.js


const data =
`<?xml version="1.0"?>
<svg xmlns="" height="100" width="100">
<circle cx="50" cy="50" r="20" fill="yellow" />
console.log(`data:image/svg+xml;charset=utf-8;base64,${btoa(unescape(encodeURIComponent(data)))}`) // Browser
console.log(`data:image/svg+xml;charset=utf-8;base64,${Buffer.from(data).toString('base64')}`) // Node.js

See also

How to add npm dependencies from multiple package registries?
How to list all files recursively within a directory tree in Node.js?
Node.js, JavaScript, TypeScript
How to receive email in Node.js?
email, Node.js, JavaScript

Made by Anton Vasetenkov.

If you want to say hi, you can reach me on LinkedIn or via email. If you like my work, you can support me by buying me a coffee.