How to Fix "Invalid Base64" Error (All Causes)

Published April 2025 · 5 min read

Getting "Invalid Base64" when trying to decode? Here are all the causes and fixes.

1. Missing Padding (=)

Base64 strings must have a length divisible by 4. Missing = padding causes errors.

// ❌ Invalid (missing padding)
SGVsbG8

// ✅ Fixed
SGVsbG8=

Fix: Add = characters until the length is divisible by 4.

function fixPadding(str) {
  return str + '='.repeat((4 - str.length % 4) % 4);
}

2. URL-Safe Base64

Some systems use URL-safe Base64 which replaces + with - and / with _.

// Convert URL-safe to standard
str.replace(/-/g, '+').replace(/_/g, '/')

3. Whitespace or Newlines

// Remove all whitespace before decoding
str.replace(/\s/g, '')

4. Not Actually Base64

The string might be URL-encoded, hex-encoded, or just plain text. Check the format first.

Test It

Use our Base64 Encoder/Decoder to test your string.

Related