Base64 is a widely used encoding technique that helps developers safely transmit and store data in text-based formats. In this article, we will understand what Base64 is, why it is used, and how to encode and decode values using Base64 in Node.js.
What is Base64 used for?
Base64 is an encoding algorithm that allows binary data (such as images, files, or encrypted values) to be converted into a printable ASCII text format. It uses only standard ASCII characters (American Standard Code for Information Interchange), making it safe for data transmission over systems that support text only.
To encode data into Base64 format, the input is first converted into binary form, then broken into groups of 6 bits. Each group is mapped to a printable ASCII character.
Why is it called Base64?
Base64 uses a set of 64 characters known as the Base64 alphabet:
A–Z, a–z, 0–9, +, and /
Since the encoding system is based on these 64 characters, it is called Base64.
For example:
- D →
RA==
- hello →
aGVsbG8=
Why is Base64 used?
- It provides a simple way to represent binary data in text format.
- Useful for systems like emails, JSON, XML, and APIs that only support text.
- Ensures data integrity during transmission.
- Supported natively by most programming languages.
- Commonly used for encoding images, tokens, files, and credentials.
Important Note:
Base64 is not an encryption method. It does not provide security and should not be used to protect sensitive information. Anyone can easily decode Base64-encoded data.
How to encode a value in Node.js using Base64?
Node.js provides a global Buffer class that can be used to encode data into Base64 format.
Example: Encoding a string into Base64
const encodedData = Buffer.from('Dummy Text', 'utf8').toString('base64');
console.log(encodedData);
This will output:
RHVtbXkgVGV4dA==
How to decode a Base64 value in Node.js?
Decoding Base64 data is just as simple. You convert the Base64 string back into its original format using the Buffer class.
Example: Decoding a Base64 string
const plainText = Buffer.from('RHVtbXkgVGV4dA==', 'base64').toString('utf8');
console.log(plainText);
This will output:
Dummy Text
Common Use Cases of Base64 in Node.js
- Encoding API tokens
- Sending images via APIs
- Storing binary data in JSON
- Email attachments
- Authentication headers
Base64 encoding is simple, powerful, and extremely useful when dealing with data transmission in Node.js applications.
Prakash Pradhan
Sr. Software Engineer
Senior Software Engineer with 10+ years of experience in designing and scaling distributed systems and full-stack applications. Experts in optimizing system performance, and delivering high-impact technical solutions across the entire software development lifecycle.
Comments
No comments yet.