Home › Resources & tools › Generating data URLs in JavaScript

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.

text/plain data

const data = 'Hello World!'
console.log(`data:text/plain;charset=utf-8,${encodeURIComponent(data)}`)

text/plain data, base64 encoding

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

text/html data, base64 encoding

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

image/svg+xml data, base64 encoding

const data =
  `<?xml version="1.0"?>
  <svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
    <circle cx="50" cy="50" r="20" fill="yellow" />
  </svg>`
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

"Hello, World!" Code Snippet Poster, JavaScript Programming Language
$14.99

A poster featuring the "Hello, World!" program in JavaScript programming language.

Big Inuktitut Syllabics
$29.99

A collection of large-format Inuktitut syllabics.

Kashubian Alphabet Poster, English-Labeled
$17.99

The Kashubian alphabet chart.

Hydrogen Peroxide Molecule Poster, Ball-and-Stick Model, English-Labeled
$19.99

A poster featuring the ball-and-stick model of the hydrogen peroxide molecule.

mainframe IPA Transcription Poster
$14.99

A poster featuring the phonetic transcription of "mainframe" in the International Phonetic Alphabet (IPA).

What are data URLs?

The ins and outs of data URLs.

Loading npm dependencies from multiple registries

How to add npm dependencies from multiple package registries?

TensorFlow.js and linear regression

Building and training simple linear regression models in JavaScript using TensorFlow.js.

Walking a directory in Node.js

How to list all files recursively within a directory tree in Node.js?

Data URI Generator

Generate data URLs in the browser.

All prices listed are in United States Dollars (USD). Visual representations of products are intended for illustrative purposes. Actual products may exhibit variations in color, texture, or other characteristics inherent to the manufacturing process. The products' design and underlying technology are protected by applicable intellectual property laws. Unauthorized reproduction or distribution is prohibited.