Back to cheatsheets
Developer
Base64 Encode / Decode
UTF-8 safe Base64 encoding and decoding, including the URL-safe variant and file conversion.
What you'll learn
- UTF-8 safe encode/decode
- URL-safe Base64
- File to Base64 data URI
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
3 ready-to-use snippets for base64 encode / decode. Click copy and paste into your project.
UTF-8 safe encode/decode
function encodeBase64(str) {
const bytes = new TextEncoder().encode(str);
return btoa(String.fromCharCode(...bytes));
}
function decodeBase64(b64) {
const bytes = Uint8Array.from(atob(b64),
c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
URL-safe Base64
function encodeBase64UrlSafe(str) {
const bytes = new TextEncoder().encode(str);
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
function decodeBase64UrlSafe(b64) {
const padded = b64
.replace(/-/g, '+')
.replace(/_/g, '/');
while (padded.length % 4) padded += '=';
const bytes = Uint8Array.from(atob(padded),
c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
File to Base64 data URI
async function fileToBase64(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(file);
});
}
// Result: "data:image/png;base64,iVBORw0KG..."
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site