fjordtools / Errors / atob: not correctly encoded

InvalidCharacterError: The string to be decoded is not correctly encoded

The browser's atob() accepts only the standard Base64 alphabet, with at most two = signs at the end. Anything else makes it throw, including the URL-safe characters - and _, a data: URI prefix, or a stray symbol. Clean the string first, then decode.

Fjordtools team · Seen in browsers and Node.js · Published · 1 min read

How browsers word it

ChromeInvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
Node.jsInvalidCharacterError: Invalid character

Common causes

  1. The URL-safe alphabet

    JWTs and many URLs use - and _ in place of + and /. atob() does not know them. The Base64 tool decodes both alphabets, with or without padding.

    Input

    -_8

    Base64 says

    Decoded: bytes FB FF
  2. A data: URI prefix

    A string such as data:image/png;base64,... carries a header before the data. Only the part after the comma is Base64.

    Input

    data:image/png;base64,iVBORw0KGgo=

    Base64 says

    Contains a character that is not Base64: ":"
  3. Padding in the wrong place

    = may only appear at the end, and at most twice. A stray = or any other symbol in the middle is invalid.

    Input

    SGVsbG8=!

    Base64 says

    Padding (=) is only allowed at the end

How to fix it

  1. Cut off any data: prefix and keep the text after the comma.
  2. Replace - with + and _ with / and add = padding to a multiple of 4, or decode with a tool that accepts Base64URL.
  3. Remove quotes, labels and other text that is not part of the Base64.
  4. Paste the string into the Base64 decoder: it says which character it does not accept.

Related errors

More error explainers are coming

See all errors.