Encode Base64 in Node.js


Here's how to encode and decode base64 in Node.js.

Encode and decode functions

This is reliable in Node.js. I've read that you can use atob and btoa now, because they're native in later versions of node. But in my experience, I didn't get them working correctly.

function encode(data) {
  return Buffer.from(JSON.stringify(data), "utf8").toString("base64");
}

function decode(base64Str) {
  return JSON.parse(Buffer.from(base64Str, "base64").toString("utf8"));
}

Test input

And now to test it out:

const data = { next: "/big/thing" };
const str = encode(data);
console.log("str=", str);
const decoded = decode(str);
console.log("decoded=", decoded);

And running it, we get this:

❯ node test.js
str= eyJuZXh0IjoiL2d1aWxkIn0=
decoded= { next: '/big/thing' }

Nothing like the smell of freshly-encode ascii in the morning.