Logo

Encode base64 in JavaScript and Decode in Python: Part 2

Learn how to decode a Base64 string you encoded from JavaScript in Python

Published: October 15, 2023

In Part 1 of this series, I encoded a string in URL-safe base64 format from my front-end application.

Recall that I encoded /Users/data/mystuff and received L1VzZXJzL2RhdGEvbXlzdHVmZg== back. Regular base64 returns L1VzZXJzL2RhdGEvbXlzdHVmZg== instead, which includes the URL-unsafe = character.

Can you decode this directly in Python? Try it now:

from base64 import urlsafe_b64decode

urlsafe_b64decode('L1VzZXJzL2RhdGEvbXlzdHVmZg'.encode('utf-8-))
>>> binascii.Error: Incorrect padding

Oops, Incorrect padding.

In Base64, the = sign is used for padding. The encoder will check if the resulting string is divisible by 4, if it’s not, it will add enough = signs for this to happen. According to the Python decoder, the = is URL-safe for some reason.

All we have to do is reconstruct the original padding:

s = 'L1VzZXJzL2RhdGEvbXlzdHVmZg'

pads_missing = len(s) % 4

if pads_missing > 0:
  s = s + ((4 - pads_missing) * "=")

urlsafe_b64decode(s.encode(‘utf-8’))

You’ll now end up with the origin L1VzZXJzL2RhdGEvbXlzdHVmZg== string.

Awesome, now you know how to send weird looking data that’s unsafe to be embedded in URLs.

💡 Need a Developer Who Gets It Done?

If this post helped solve your problem, imagine what we could build together! I'm a full-stack developer with expertise in Python, Django, Typescript, and modern web technologies. I specialize in turning complex ideas into clean, efficient solutions.