Ctrl + K
Encoding24 min read

Data URI Explained

A practical guide to Data URIs and Data URLs, covering their syntax, Base64 encoding, images, SVG, CSS, HTML, JavaScript, MIME types, browser behavior, security, performance and common mistakes.

Published: 2026-10-05

A web page normally loads resources such as images, fonts, stylesheets and scripts from separate URLs. A Data URI provides another option: the resource can be represented directly inside a URL-like string and embedded into HTML, CSS, JavaScript or another document.

Data URIs are especially useful for small resources. A tiny image, SVG icon, generated asset or other piece of data can be placed directly into a document without requiring a separate resource URL.

The technique is simple, but using it effectively requires understanding MIME types, URL encoding, Base64, browser limits, caching, security policies and performance trade-offs. A Data URI can be convenient for a small asset while being a poor choice for a large production image.

What Is a Data URI?

A Data URI is a URI that contains the actual data instead of pointing to a separate resource. The browser can interpret the URI and use the embedded data as the requested resource.

data:text/plain,Hello%20World

The example represents a plain-text resource containing the words Hello World. Nothing needs to be downloaded from another URL because the data is already contained in the URI.

The modern specification generally refers to these as Data URLs, although the older and still very common term Data URI is widely used by developers.

Data URI vs Data URL

In everyday web development, Data URI and Data URL usually refer to the same mechanism. The term Data URL emphasizes that the value can be used where a URL is accepted, while Data URI is the older terminology that remains common in documentation and developer tools.

You will therefore see both terms used for strings beginning with data:. When discussing browser development, treating them as the same mechanism is normally sufficient.

Basic Data URI Syntax

A Data URI begins with the data: scheme. It can then specify a media type, optional parameters, an optional Base64 indicator, and the actual data.

data:[<media-type>][;base64],<data>
PartExamplePurpose
Schemedata:Identifies the value as a Data URL
Media typeimage/pngDescribes the type of embedded resource
Parametercharset=utf-8Provides additional information about the data
Encoding indicatorbase64Indicates that the data is Base64 encoded
DataHello%20WorldContains the actual resource data

Not every Data URI needs every component. The media type can be omitted when the default is appropriate, and Base64 is optional. The important distinction is whether the data is represented directly using URL syntax or encoded using Base64.

A Simple Text Data URI

The simplest useful example contains text directly in the URI.

data:text/plain,Hello%20World

The space is represented as %20 because spaces and other characters may need URL encoding. The browser decodes the URL representation and obtains the original text.

Data URIs with Base64

Binary resources contain arbitrary bytes, so representing them directly as URL text can be inconvenient. Base64 provides a way to convert those bytes into a text representation.

data:text/plain;base64,SGVsbG8gV29ybGQ=

The base64 parameter tells the consumer that the data portion should be decoded from Base64 before being interpreted as the resource.

Base64 is not mandatory for all Data URIs. It is particularly useful for binary data and situations where representing the resource directly would require extensive escaping.

URL Encoding vs Base64 in Data URIs

ApproachExampleTypical use
Direct URL-encoded datadata:text/plain,Hello%20WorldSmall text resources
Base64 datadata:text/plain;base64,SGVsbG8=Binary data and convenient embedding

For text-based resources such as small SVG documents, URL encoding can sometimes produce a smaller or more readable result than Base64. For binary data such as PNG images, Base64 is often much more convenient.

💡 Do not automatically Base64-encode every Data URI. For small text resources, direct URL encoding can sometimes be more compact and easier to inspect.

Data URIs in HTML

One of the most familiar Data URI use cases is embedding an image directly into an HTML document. The src attribute can contain the complete Data URL instead of an external image URL.

<img
  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  alt="Embedded image"
/>

The browser sees the data: scheme, determines that the resource is an image, decodes the Base64 content, and renders the resulting image.

The same general idea can be used with other HTML elements and resource types when the relevant browser and security policies allow it.

Embedding SVG in HTML

SVG is particularly interesting because it is already a text-based format. A small SVG can be represented directly as a Data URI without necessarily using Base64.

<img
  src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3C%2Fsvg%3E"
  alt="Embedded SVG"
/>

The SVG markup has been URL-encoded so that characters with special meaning in URL syntax do not interfere with the Data URI.

Base64 is another option for SVG and is often easier to generate automatically, especially when the SVG contains many characters that would otherwise need encoding.

Data URIs in CSS

CSS can use Data URLs anywhere a resource URL is accepted. The most common example is an embedded background image.

.icon {
  background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...");
}

This can be convenient for very small icons, generated backgrounds, patterns and other resources that are tightly coupled to a stylesheet.

CSS Background Data URIs

A Data URI can replace a normal image URL in background-image declarations.

.background {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAA...");
}

The browser decodes the embedded data and uses it as the background resource. This can eliminate a separate network request, but that does not automatically mean the page becomes faster.

With modern HTTP versions, browsers can efficiently download multiple resources, and external resources can be cached independently. Embedding an asset into CSS can instead increase the size of the stylesheet and prevent that asset from being independently cached.

Data URIs in JavaScript

JavaScript can construct and use Data URLs dynamically. This is useful when an application generates content in the browser and needs to display it temporarily.

const dataUrl = "data:text/plain;charset=utf-8,Hello%20World";

const link = document.createElement("a");
link.href = dataUrl;
link.textContent = "Open data";

document.body.appendChild(link);

Client-side applications can also generate Data URLs from Blob or binary data when a browser API specifically benefits from a URL representation.

Data URIs for Generated Downloads

A small generated resource can sometimes be offered to the user through a Data URL. This is useful for tiny text files, simple generated content, and demonstrations.

<a
  href="data:text/plain;charset=utf-8,Hello%20World"
  download="example.txt"
>
  Download
</a>

For larger files, Blob URLs are generally a better browser-side mechanism because Data URLs require the entire resource to be represented as a string.

Data URI vs Blob URL

PropertyData URIBlob URL
Data locationEmbedded directly in the stringReferences a browser-managed Blob
RepresentationTextBrowser object URL
Large resourcesUsually inefficientGenerally more appropriate
Self-containedYesNo
Typical useSmall embedded resourcesGenerated or temporary browser resources

A Blob URL can be a better choice when JavaScript generates a larger file or binary resource. The browser can work with the Blob without forcing the entire resource into a large Data URL string.

Data URIs for Small Icons

Small icons are one of the more reasonable uses for Data URIs. If an icon is tiny and only needed together with a particular stylesheet or document, embedding it can simplify resource management.

The trade-off becomes less attractive when the same icon is used throughout a large site. An external resource can be cached once and reused across many pages, while an embedded Data URI may be duplicated in every document or stylesheet containing it.

Data URIs for SVG Icons

SVG icons are especially suitable for compact Data URLs because SVG source can be small and remains scalable. A generated SVG Data URI can be placed into CSS backgrounds, HTML image elements, or other contexts that accept image URLs.

data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%3E...%3C%2Fsvg%3E

Because SVG is text-based, developers have a choice between URL encoding and Base64. URL encoding can preserve more readable structure, while Base64 can simplify the escaping process.

Data URIs for Fonts

CSS can also represent font resources using Data URLs. A font file can be encoded and referenced from an @font-face declaration.

@font-face {
  font-family: "EmbeddedFont";
  src: url("data:font/woff2;base64,d09GMgABAAAAA...") format("woff2");
}

Although technically possible, embedding fonts as Data URLs is usually something to evaluate carefully. Fonts can be relatively large and are often shared across many pages, making independently cached external font files more practical.

Data URIs for Audio and Video

Data URLs can represent audio or video resources when the browser and surrounding context permit them. However, multimedia files are generally much larger than the resources for which Data URLs are most useful.

Embedding a large video or audio file directly into HTML creates a very large document and prevents the resource from behaving like an independently managed media file. Normal URLs, streaming mechanisms and appropriate media delivery are usually better choices.

⚠️ Data URLs are technically capable of representing large resources, but technical possibility does not make the approach practical. Large images, audio and video should normally remain separate resources.

MIME Types in Data URIs

The media type tells the browser what kind of data is being embedded. Correctly specifying the MIME type helps the browser interpret the decoded content as the intended resource.

ResourceMIME typeExample prefix
PNG imageimage/pngdata:image/png;base64,...
JPEG imageimage/jpegdata:image/jpeg;base64,...
SVG imageimage/svg+xmldata:image/svg+xml;base64,...
Plain texttext/plaindata:text/plain,...
CSStext/cssdata:text/css,...
JavaScripttext/javascriptdata:text/javascript,...
WOFF2 fontfont/woff2data:font/woff2;base64,...

The MIME type describes the data; it does not determine whether Base64 is being used. The base64 parameter and the actual representation of the data are separate parts of the Data URL.

Charset in Data URIs

Text-based Data URLs can specify a character set, such as UTF-8. This can be useful when the embedded data contains characters outside the basic ASCII range.

data:text/plain;charset=utf-8,Hello%20World

For Base64 data, the encoded representation consists of ASCII characters, but the bytes represented by that Base64 value can still correspond to UTF-8 or another character encoding.

Data URIs and HTML Encoding

Data URL encoding and HTML entity encoding are different things. A character may need to be represented safely for HTML syntax, while the data portion of the URI may independently need URL encoding.

For example, embedding a Data URL into an HTML attribute means the developer must consider both the syntax of the HTML attribute and the syntax of the Data URL itself.

💡 Think about the layers separately: HTML escaping protects the HTML document, URL encoding represents characters safely in the Data URL, and Base64 represents bytes as text.

Data URI Size Overhead

One of the biggest disadvantages of Base64 Data URLs is size. Base64 converts three bytes into four characters, producing roughly 33% expansion before additional formatting is considered.

Original binary sizeApproximate Base64 representation
3 KB4 KB
30 KB40 KB
300 KB400 KB
3 MB4 MB

Direct URL encoding of text can have different overhead characteristics. For this reason, it is useful to evaluate the actual representation instead of assuming that Base64 is always the smallest Data URI format.

Data URIs and Browser Caching

A separate resource URL can be cached independently by the browser. A Data URI embedded in an HTML document or stylesheet is part of that containing resource.

If the same image is embedded into ten pages, each page can contain its own copy of the Data URI. With an external image URL, the browser can potentially reuse the cached image between pages.

This makes caching an important consideration when deciding whether to embed an asset. Eliminating a network request is not automatically beneficial if it causes the same bytes to be duplicated across many responses.

Data URIs and HTTP Requests

A Data URI can eliminate a separate request for the embedded resource because the resource is already present in the containing document. This was particularly attractive when reducing the number of HTTP requests was a major optimization strategy.

Modern HTTP/2 and HTTP/3 changed the performance landscape. Browsers can efficiently handle many concurrent resources, so embedding everything into CSS or HTML is no longer automatically a performance improvement.

The correct decision depends on resource size, reuse, caching, critical rendering behavior, compression, and the structure of the application.

Data URI Compression

Data URIs are not themselves a compression mechanism. A Base64 Data URI generally contains more characters than the original binary data.

However, the containing HTML or CSS can still be compressed using Brotli or gzip when transferred over HTTP. The final network cost therefore depends on both the Data URI representation and the compression applied to the surrounding response.

For highly repetitive or compressible content, transfer compression can reduce some of the textual overhead. That does not eliminate the disadvantages of embedding large resources or losing independent caching.

Data URI Security

Data URLs are not inherently malicious or insecure. They are simply another way of representing data. However, accepting arbitrary Data URLs can create security concerns depending on where they are used and what content types are allowed.

For example, an application that accepts user-controlled URLs should not assume that every URL is an ordinary external image URL. Data URLs can represent different types of content, and browser security policies determine which contexts can execute or load that content.

Content Security Policy and Data URLs

Content Security Policy can restrict which sources are allowed for different resource types. A CSP may allow or block data: sources depending on the directives configured by the application.

Content-Security-Policy: img-src 'self' data:;

This example allows images to be loaded from the site's own origin and from Data URLs. Whether data: should be allowed depends on the application's requirements. Broadly permitting data: for script or other executable contexts can create unnecessary security exposure.

⚠️ Do not add data: to every Content Security Policy directive simply to make an embedded resource work. Allow it only for the resource types and use cases that actually require it.

Data URIs and XSS

Data URLs can become relevant to cross-site scripting defenses when an application accepts user-controlled URLs or markup. The security impact depends on the browser context, allowed schemes, MIME types, CSP configuration and how the value is inserted into the page.

A common defensive approach is to validate URLs against an explicit allowlist of accepted schemes and resource types rather than accepting arbitrary values. If an application only needs images, for example, its URL validation can be much narrower than a system that accepts arbitrary navigation URLs.

Data URI vs External Resource

PropertyData URIExternal resource
Separate requestNoUsually yes
Independent cachingNoYes
Self-containedYesNo
Large resourcesUsually poor fitUsually better
Small embedded assetsConvenientRequires separate resource
Reuse across pagesCan duplicate dataCan share cached resource

When Data URIs Are a Good Choice

Data URIs are most useful when the resource is small, closely tied to the document using it, and unlikely to benefit substantially from independent caching.

  • Tiny SVG icons.
  • Small CSS background images.
  • Self-contained HTML demonstrations.
  • Generated previews.
  • Small images embedded in generated documents.
  • Temporary browser-generated content.
  • Small resources required by a text-only interface.

When Data URIs Are a Poor Choice

Data URIs become less attractive as the resource grows or needs to be reused independently.

  • Large photographs.
  • Large PNG or JPEG files.
  • Audio files.
  • Video files.
  • Large fonts.
  • Assets shared across many pages.
  • Resources that need independent browser caching.
  • Files that need to be replaced or updated independently from the document.

Data URIs for Images: Practical Guidelines

For small images, a Data URI can be perfectly reasonable. For larger production images, an ordinary image URL is usually easier to optimize, cache and manage.

  • Use normal image URLs for substantial production images.
  • Consider Data URLs for tiny icons and tightly coupled assets.
  • Avoid embedding the same large image into many pages.
  • Consider browser caching before replacing external assets with Data URLs.
  • Use an appropriate image format before Base64 encoding.
  • Remember that Base64 adds roughly one-third to the binary representation.

Data URIs for SVG: Practical Guidelines

SVG is one of the most useful formats for Data URIs because small vector graphics can remain compact. The choice between direct URL encoding and Base64 depends on the SVG content and where it will be embedded.

  • Use Data URLs for small, reusable-in-context SVG icons.
  • Prefer URL encoding when it produces a smaller and manageable representation.
  • Use Base64 when escaping the SVG manually would be cumbersome.
  • Keep large SVG illustrations as normal resources.
  • Sanitize SVG content when it comes from untrusted users.

Data URIs and Untrusted SVG

SVG is an active document format with capabilities beyond simple pixel data. When SVG content comes from an untrusted source, embedding it directly without appropriate sanitization can introduce security risks.

Encoding an SVG as Base64 does not make the SVG trustworthy. Base64 changes the representation of the bytes but does not remove potentially unsafe content from those bytes.

⚠️ Never treat Base64 encoding as SVG sanitization. If users can supply SVG content, validate and sanitize it according to the application's security requirements before rendering it.

Data URIs in React and Next.js

React applications can use Data URLs in attributes such as src and style values when the relevant browser and security policies allow them.

const iconSrc =
  "data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...";

export function Icon() {
  return <img src={iconSrc} alt="Icon" />;
}

For a small generated preview, this can be convenient. For production assets, framework-specific image handling and normal static resources are often better because they support caching, optimization and independent delivery.

In Next.js applications, it is especially important to distinguish between a tiny embedded asset and a real application image. A Data URI should not be used simply because it is possible to put an image into a string.

Creating a Data URI from Base64

If an image has already been converted to Base64, constructing a Data URL is straightforward. The MIME type must match the actual resource.

const base64 = "iVBORw0KGgoAAAANSUhEUgAA...";
const dataUrl = `data:image/png;base64,${base64}`;

console.log(dataUrl);

The prefix is important. A raw Base64 string does not tell the browser that it represents a PNG, SVG, JPEG or another resource. The Data URL provides that context.

Converting an Image to a Data URI

A typical image-to-Data-URI workflow involves reading the image bytes, encoding them as Base64, and prepending the appropriate MIME type.

Image bytes
Base64 encoding
Add MIME type
Add data: prefix
Use as a Data URL

A browser application can obtain the MIME type from a File object, while a server application can determine it from the file metadata or a trusted source. The MIME type should correspond to the actual content.

Decoding a Data URI

Decoding a Data URI involves identifying its media type and representation, extracting the data portion, and decoding it when necessary. If the URI uses Base64, the Base64 section must be decoded back into bytes.

For text resources represented directly in the URI, URL decoding may be sufficient. For binary resources, the decoded bytes can then be used to reconstruct a Blob, File or other binary representation.

Common Data URI Mistakes

  • Forgetting the correct MIME type.
  • Forgetting the base64 indicator when the data is Base64 encoded.
  • Trying to use Base64 as encryption.
  • Embedding large files directly into HTML or CSS.
  • Ignoring browser caching consequences.
  • Using data: unnecessarily in a Content Security Policy.
  • Assuming Base64 and URL encoding are interchangeable.
  • Embedding untrusted SVG without sanitization.
  • Using a Data URL when a Blob URL or normal resource URL is more appropriate.
  • Putting user-controlled Data URLs into security-sensitive contexts without validation.

Data URI Troubleshooting

When a Data URI does not work, the problem is often related to the prefix, encoding, MIME type or surrounding syntax.

ProblemPossible cause
Image does not displayIncorrect MIME type or corrupted Base64 data
Base64 image appears brokenMissing or incorrect data URL prefix
SVG does not renderInvalid SVG or incorrect URL encoding
CSP blocks the resourcedata: is not allowed by the relevant CSP directive
Text appears corruptedIncorrect character encoding or decoding
Very large HTML or CSSEmbedded resources are too large

When debugging, first separate the problem into layers: verify the original data, verify the encoding, verify the Data URI prefix, and then check the browser context and security policy.

Data URI vs Base64

A Data URI and Base64 are not the same thing. A Data URI is a complete resource representation that begins with data:. Base64 is one possible encoding used for the data portion.

ConceptMeaning
Data URIA URI containing the resource data
Base64An encoding that can represent bytes as text
MIME typeDescribes what the embedded data represents
URL encodingRepresents characters safely in URL syntax

This distinction is important because a Data URI can contain directly represented data without Base64. Conversely, a Base64 string does not automatically become a Data URI until the appropriate data: prefix and metadata are added.

Data URI vs Inline SVG

Inline SVG and SVG Data URLs both allow SVG content to be embedded into a page, but they work differently. Inline SVG places the SVG markup directly into the HTML document, while an SVG Data URL represents the SVG as a URL value.

PropertyInline SVGSVG Data URI
Markup locationDirectly in HTMLInside a URL value
CSS backgroundNot directly applicableConvenient
Direct DOM accessYesNo in the same direct way
Text readabilityUsually higherDepends on encoding
Typical useInteractive or styled SVGEmbedded image or CSS resource

If the application needs to manipulate SVG elements directly through the DOM, inline SVG can be more appropriate. If the SVG is simply an image resource for a CSS background or image element, a Data URL can be convenient.

A Practical Data URI Decision Guide

RequirementRecommended approach
Tiny image embedded in one documentData URI can be appropriate
Large production imageNormal image URL
Small SVG used as CSS backgroundSVG Data URI can be appropriate
Interactive SVGInline SVG
Large browser-generated fileBlob URL
Reusable site-wide assetExternal resource
Binary value required inside JSONBase64 or protocol-specific representation
Sensitive dataUse appropriate security mechanisms, not Data URI encoding

Frequently Asked Questions

What is a Data URI?

A Data URI is a URI that contains the actual resource data instead of pointing to a separate resource. It begins with data: and can represent text, images, SVG, fonts and other types of content.

Is a Data URI the same as Base64?

No. A Data URI is the complete representation beginning with data:. Base64 is only one possible way to encode the data portion. A Data URI can also contain directly represented and URL-encoded text.

Why use Base64 in a Data URI?

Base64 provides a convenient text representation of arbitrary bytes, making it particularly useful for binary resources such as PNG and JPEG images. It is not mandatory for every Data URI.

Are Data URIs good for website images?

They can be useful for very small images and icons, but normal image URLs are usually better for larger or frequently reused images because they support independent caching and avoid embedding the entire resource into HTML or CSS.

Can I use a Data URI in CSS?

Yes. Data URLs can be used in CSS properties such as background-image and can be particularly convenient for small SVG icons and other tiny assets.

Are Data URIs secure?

A Data URI is not inherently unsafe, but applications should validate untrusted Data URLs and consider their Content Security Policy. Base64 encoding does not provide security or sanitize potentially dangerous content.

Can Data URIs contain SVG?

Yes. SVG can be represented directly using URL encoding or encoded as Base64. For untrusted SVG content, appropriate sanitization is still necessary because Base64 does not remove unsafe markup or behavior.

Helpful Data URI and Encoding Tools

An SVG Data URI Generator can turn SVG markup into an embeddable Data URL, which is especially useful for CSS backgrounds and small image resources. An Image to Base64 Converter can convert image files into Base64 data that can then be placed inside a Data URI, while a Base64 Encoder / Decoder is useful for inspecting or transforming the encoded portion. A CSS Background Generator can help create CSS declarations containing image resources, and an HTML Formatter can make surrounding HTML easier to read when working with embedded assets.

Conclusion

Data URIs provide a convenient way to embed small resources directly into HTML, CSS, JavaScript and other documents. They are especially useful for small SVG icons, tiny images, generated content and self-contained examples where avoiding a separate resource URL is valuable.

The main trade-offs are size, caching and maintainability. Base64-encoded Data URIs are larger than the original binary data, and embedding an asset prevents it from being cached as an independent resource. These costs become increasingly important as the resource grows or is reused across many pages.

The best approach is therefore to use Data URIs selectively. They are a useful tool for small, tightly coupled resources, but normal URLs, Blob URLs, inline SVG or other resource-delivery mechanisms are often better for larger or reusable content.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.