How to Do Base64 Encoding in Node.js?

Node.js makes Base64 conversion easy. Use Buffer to encode or decode strings and files directly ideal for authentication and web APIs.

Summarize with AI

Not enough time? get the key points instantly.

Base64 encode and decode strings or files using Node.js’s Buffer class. Perfect for API tokens, image handling or data formatting.

Problem

In many development scenarios like API auth, file transfer or embedding images into HTML you need to Base64 encode data. While there are third party libraries, Node.js has a native way to do Base64 encoding and decoding.

Solution

Node.js has a built in Buffer class to encode and decode data without any external modules.

Base64 encode a string

const data = ‘Hello, eSparkBiz!’;const encoded = Buffer.from(data).toString(‘base64’);

console.log(encoded); // SGVsbG8sIGVTcGFya0JpeiE=

Base64 decode a string

const decoded = Buffer.from(encoded, ‘base64’).toString(‘utf8’);console.log(decoded); // Hello, eSparkBiz!

Also Read:

Base64 encode a file (like an image)

const fs = require(‘fs’);const image = fs.readFileSync(‘logo.png’);

const base64Image = image.toString(‘base64’);

This is useful when embedding small images in HTML or sending file data over JSON or HTTP requests.

Conclusion

Base64 in Node.js is easy with the Buffer class. It’s perfect for converting strings or files to a format used in web development, APIs and secure transmission.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…