Base64 Encoding and Decoding: When to Use It and When Not
Base64 looks like magic but it has real limits. Here is how I use it correctly and where I have seen it cause problems. Base64 is the encoding I reach for when I need to move binary data through a text channel. Embed an image in a data URL, send a file payload in a JSON field, store binary blobs in a system that only accepts strings. The encoding works and is well supported in every language and every browser. The problems start when I treat Base64 as something it is not: compression, obfuscation, or encryption. Here is how I use it correctly and where I have seen it misused. Base64 Inflates Size, It Does Not Compress The first thing to know about Base64 is that it makes data bigger, by about one third. Three bytes of binary become four characters of Base64. Adding twelve characters to a fifty-byte payload is no big deal. Adding twelve megabytes to a thirty-megabyte payload is a real cost. When I see people use Base64 as a way to fit more data in a field, sometimes they expect the encoding to shrink the value, and the opposite happens. I check the size impact before encoding. For small payloads under a few kilobytes, the inflation is negligible. For larger payloads, especially those that travel over slow connections or sit in storage for long periods, I look for alternatives. Storing the binary in object storage and keeping a reference in the text field is usually cheaper and faster. Base64 in the database column is convenient and slow. Base64 Is Not Obfuscation Base64 is reversible by anyone who can run a decoder, which is everyone. Encoding a string in Base64 does not hide its contents. It changes the representation in a way that is trivial to reverse. I have seen Base64 used to hide API keys, passwords, internal identifiers, and license tokens. Nothing is hidden. The encoded value is the original value in a different alphabet, and the decoder is in every standard library in existence. For anything that must not be readable by the recipient, use encryption with a real key. For anything that should not be casually inspected, like a session token, use a signed token format designed for the purpose. Base64 is fine for moving data through systems that choke on binary, and that is its legitimate role. It is not security and treating it as security has been the root cause of multiple real breaches I read about. Strip the Data URL Prefix When Storing When I embed an image in a data URL, the prefix data:image/png;base64, sits in front of the actual Base64 string. The prefix is useful for inlining into a page and useless for storage. Storing the prefix costs bytes and adds a parsing step on read. I strip the prefix when I store the encoded value and add it back when I render. This guide is part of the KitCraft Blog, where every tutorial pairs with a free browser-based tool — try the related tool while you read.