Blob URLs and Object URLs in Web Applications
Understand blob: URLs created by URL.createObjectURL(), how they work, their lifecycle, memory management, and practical uses in file uploads, downloads, and media streaming.
Detailed Explanation
Blob URLs (Object URLs)
Blob URLs are temporary URLs that reference in-memory data objects in the browser. They are created using URL.createObjectURL() and follow the format blob:origin/uuid.
Creating Blob URLs
// From a File input
const file = document.getElementById("upload").files[0];
const blobUrl = URL.createObjectURL(file);
// "blob:https://example.com/550e8400-e29b-41d4-a716-446655440000"
// From a Blob
const blob = new Blob(["Hello, World!"], { type: "text/plain" });
const textUrl = URL.createObjectURL(blob);
Structure
blob:https://example.com/550e8400-e29b-41d4-a716-446655440000
\__/ \_________________/ \____________________________________/
| | |
scheme origin UUID
- Scheme — always
blob: - Origin — the origin of the page that created it
- UUID — a unique identifier for the in-memory object
Common Uses
Image preview before upload:
fileInput.addEventListener("change", (e) => {
const url = URL.createObjectURL(e.target.files[0]);
previewImg.src = url;
});
Client-side file download:
const csv = "name,age\nAlice,30\nBob,25";
const blob = new Blob([csv], { type: "text/csv" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "data.csv";
link.click();
Video/Audio streaming:
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
Memory Management
Blob URLs hold a reference to the underlying data in memory. They must be explicitly revoked to free memory:
const url = URL.createObjectURL(blob);
// ... use the URL ...
URL.revokeObjectURL(url); // Free memory
Important Characteristics
- Blob URLs are same-origin only — they cannot be used cross-origin
- They are temporary — they only last for the lifetime of the document
- They are not shareable — other users/tabs cannot access them
- They do not survive page refresh
- They cannot be parsed by
new URL()in most browsers
Use Case
Blob URLs are essential for building file upload interfaces with previews, client-side file generators (PDF, CSV, ZIP), video/audio players with MediaSource, and canvas-to-image exports. Understanding their lifecycle prevents memory leaks in long-running applications that handle many files.