Error Encyclopedia

Invalid Base64 Decoding Error

Fix 'Invalid base64 string' errors when decoding Base64 data in JavaScript, Python, and other languages.

What Does This Error Mean?

The 'Invalid base64 string' error occurs when trying to decode a string that is not valid Base64. Common issues include incorrect padding, invalid characters, or using the wrong Base64 variant (standard vs URL-safe).

Common Causes

1

Missing or incorrect Base64 padding (= or == at the end)

2

Invalid characters not in the Base64 alphabet

3

Using URL-safe Base64 where standard Base64 is expected or vice versa

4

Newlines or whitespace in the Base64 string

5

Data URI prefix (data:image/png;base64,) included in the decode input

How to Fix It

Fix padding

Base64 strings must have proper padding. Add or correct padding characters.

// Fix padding in JavaScript
function fixBase64Padding(str) {
  const pad = str.length % 4
  if (pad === 2) return str + "=="
  if (pad === 3) return str + "="
  return str
}

// In Python
import base64
def fix_padding(s):
    return s + "=" * (4 - len(s) % 4) if len(s) % 4 else s

Convert URL-safe to standard Base64

URL-safe Base64 uses - and _ instead of + and /. Convert before decoding.

// JavaScript: convert URL-safe to standard Base64
function fromUrlSafeBase64(str) {
  return str
    .replace(/-/g, "+")
    .replace(/_/g, "/")
}

// Python
import base64
def from_url_safe(s):
    return s.replace("-", "+").replace("_", "/")

# Decode URL-safe directly with urlsafe_b64decode
base64.urlsafe_b64decode(url_safe_string)

Strip whitespace and prefixes

Remove whitespace and data URI prefixes before decoding.

// JavaScript: clean before decoding
function cleanBase64(str) {
  return str
    .replace(/^data:[^;]+;base64,/, "")  // Strip data URI prefix
    .replace(/\s/g, "")                  // Remove whitespace
}

// Python
import re
def clean_base64(s):
    s = re.sub(r"^data:[^;]+;base64,", "", s)
    return s.replace("\n", "").replace(" ", "")

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: