How do you convert a string to base64 and back in Node.js?
Use Buffer.from(text, "utf8").toString("base64") to encode and Buffer.from(b64, "base64").toString("utf8") to decode. Base64 is an encoding for transport, not encryption.
Explain it simply
Some channels, like email bodies or JSON, handle plain text safely but choke on raw bytes. Base64 rewrites any bytes using only 64 safe characters (A-Z, a-z, 0-9, plus and slash). It is like writing a Hindi message in Roman letters so a basic keyboard can carry it. Anyone can reverse it, so it hides nothing.
Example
const text = "namaste";
const b64 = Buffer.from(text, "utf8").toString("base64");
console.log(b64); // bmFtYXN0ZQ==
const back = Buffer.from(b64, "base64").toString("utf8");
console.log(back); // namaste
// hex and url-safe variants
console.log(Buffer.from(text).toString("hex")); // 6e616d61737465
console.log(Buffer.from(text).toString("base64url"));Where you meet it:
- HTTP Basic authentication header:
Authorization: Basic base64(user:password). - The header and payload parts of a JWT, using the base64url variant.
- Embedding small images as data URLs.
Base64 makes data about one third larger. In browsers use btoa and atob, which work on plain strings; in Node, Buffer handles Unicode correctly.
What to say in the interview
"Buffer.from with an encoding and toString with another one converts between them. Base64 is only a reversible encoding for safe transport, so I never treat it as a way of protecting secrets."
Common mistakes
- Thinking base64 encrypts data.
- Forgetting the encoding argument when decoding, which treats the string as UTF-8.