Base64 and hex encoding
suggest changeBinary data (images, hashes, encryption keys, random tokens) can't be safely put into JSON, URLs, HTTP headers or text files as raw bytes. The usual fix is to encode the bytes as text:
- hex (base16) uses 2 characters (
0-9a-f) per byte. It's easy to read and debug but doubles the size. - base64 uses 4 characters per 3 bytes (
A-Z a-z 0-9 + /plus=padding). Output is about 33% bigger than the input. - base64url is base64 with
-and_instead of+and/, and no padding. It's safe in URLs, file names and cookies.
In Node.js the main tool for this is Buffer, which can convert between bytes and all of these encodings.
Encoding and decoding with Buffer
Buffer.from(string, encoding) decodes a string into bytes and buf.toString(encoding) encodes bytes into a string:
const buf = Buffer.from('Hello, Node!', 'utf8');
const b64 = buf.toString('base64');
const b64url = buf.toString('base64url');
const hex = buf.toString('hex');
console.log(b64); // SGVsbG8sIE5vZGUh
console.log(b64url); // SGVsbG8sIE5vZGUh
console.log(hex); // 48656c6c6f2c204e6f646521
// decode back to bytes, then to a UTF-8 string
console.log(Buffer.from(b64, 'base64').toString('utf8')); // Hello, Node!
console.log(Buffer.from(hex, 'hex').toString('utf8')); // Hello, Node!
console.log(Buffer.from(b64url, 'base64url').toString()); // Hello, Node!
Buffer is a global, but you can also import it explicitly with import { Buffer } from 'node:buffer'. The default encoding for toString() is 'utf8'.
A few small helpers cover most needs:
const toBase64 = (str) => Buffer.from(str, 'utf8').toString('base64');
const fromBase64 = (b64) => Buffer.from(b64, 'base64').toString('utf8');
console.log(toBase64('zażółć gęślą jaźń')); // works with any Unicode text
console.log(fromBase64(toBase64('zażółć gęślą jaźń')));
base64 vs. base64url
The difference shows up when the bytes produce +, / or padding:
const bytes = Buffer.from([0xfb, 0xff]);
console.log(bytes.toString('base64')); // +/8=
console.log(bytes.toString('base64url')); // -_8
+, / and = have special meaning in URLs and query strings, so use base64url for tokens that end up in links, JWTs, or file names. The 'base64url' encoding was added in Node.js 15.7 / 14.18.
When decoding, Node.js is lenient: 'base64' accepts both alphabets and missing padding, so Buffer.from(x, 'base64') will decode base64url input too.
Hex encoding
Hex is the standard way to display hashes, checksums and binary IDs:
import { createHash, randomBytes } from 'node:crypto';
// digest() can return hex or base64 directly
const sha = createHash('sha256').update('hello').digest('hex');
console.log(sha);
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
const shaB64 = createHash('sha256').update('hello').digest('base64');
console.log(shaB64); // LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=
// random 16-byte ID as 32 hex chars
console.log(randomBytes(16).toString('hex'));
To convert a hex string to bytes and back:
const key = Buffer.from('00ff10a0', 'hex');
console.log(key); // <Buffer 00 ff 10 a0>
console.log(key.length); // 4
console.log(key.toString('hex')); // 00ff10a0
Decoding hex is case-insensitive ('FF' and 'ff' give the same byte), but toString('hex') always produces lowercase. Use .toUpperCase() if you need uppercase.
Validating input
Buffer.from() does not throw on malformed input. It silently skips or truncates, which can hide bugs:
// hex decoding stops at the first invalid character
console.log(Buffer.from('zz12', 'hex')); // <Buffer >
console.log(Buffer.from('12zz', 'hex')); // <Buffer 12>
// an odd trailing character is dropped
console.log(Buffer.from('abc', 'hex')); // <Buffer ab>
// base64 decoding ignores characters outside the alphabet
console.log(Buffer.from('aGV@@sbG8=', 'base64').toString()); // hello
If the data comes from users or external systems, validate it first:
function decodeHex(str) {
if (str.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(str)) {
throw new Error(`invalid hex string: ${str}`);
}
return Buffer.from(str, 'hex');
}
function decodeBase64(str) {
// standard alphabet, optional padding
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str) || str.length % 4 === 1) {
throw new Error('invalid base64 string');
}
return Buffer.from(str, 'base64');
}
console.log(decodeHex('cafe')); // <Buffer ca fe>
console.log(decodeBase64('aGVsbG8=')); // <Buffer 68 65 6c 6c 6f>
A simpler alternative for base64 is a round-trip check: decode, re-encode, and compare with the (normalized) input.
Computing sizes without decoding
Buffer.byteLength() tells you how many bytes a string decodes to, which is handy for enforcing upload limits before allocating memory:
const b64 = 'aGVsbG8gd29ybGQ=';
console.log(Buffer.byteLength(b64, 'base64')); // 11
console.log(b64.length); // 16
// encoded length of n bytes: 4 * Math.ceil(n / 3) for padded base64
const encodedLength = (n) => 4 * Math.ceil(n / 3);
console.log(encodedLength(11)); // 16
Data URLs and files
Base64 is often used to embed small files in HTML, CSS or JSON:
import { readFile, writeFile } from 'node:fs/promises';
// file -> data URL
const png = await readFile('logo.png');
const dataUrl = `data:image/png;base64,${png.toString('base64')}`;
// data URL -> file
const [, payload] = dataUrl.split(',', 2);
await writeFile('logo-copy.png', Buffer.from(payload, 'base64'));
readFile and writeFile also accept an encoding directly: readFile('logo.png', 'base64') returns a base64 string and writeFile('out.bin', b64, 'base64') decodes before writing.
HTTP Basic authentication
The Authorization: Basic header is username:password encoded as base64:
const user = 'alice';
const password = 's3cret';
const token = Buffer.from(`${user}:${password}`).toString('base64');
const res = await fetch('https://example.com/api', {
headers: { Authorization: `Basic ${token}` },
});
// parsing it on the server side
function parseBasicAuth(header) {
const [scheme, value] = (header ?? '').split(' ');
if (scheme !== 'Basic' || !value) return null;
const decoded = Buffer.from(value, 'base64').toString('utf8');
const i = decoded.indexOf(':');
if (i < 0) return null;
return { user: decoded.slice(0, i), password: decoded.slice(i + 1) };
}
Remember that base64 is an encoding, not encryption. Anyone can decode it, so Basic auth must be used over HTTPS.
Encoding streams
For large files, don't load everything into memory. Readable streams accept an encoding via setEncoding() and correctly handle chunk boundaries (base64 works in groups of 3 bytes, so naively encoding each chunk separately would insert padding in the middle):
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
const input = createReadStream('video.mp4');
input.setEncoding('base64');
await pipeline(input, createWriteStream('video.mp4.b64'));
btoa() and atob()
Node.js also provides the browser globals btoa() and atob(). They are kept for web compatibility and are considered legacy: they work on "binary strings" (one character per byte), so they fail on Unicode text:
console.log(btoa('hello')); // aGVsbG8=
console.log(atob('aGVsbG8=')); // hello
try {
btoa('zażółć');
} catch (err) {
console.log(err.name); // InvalidCharacterError
}
In Node.js code prefer Buffer. In code shared with browsers, use the Uint8Array methods described next.
Uint8Array.fromBase64() and toHex()
Newer JavaScript engines implement standard base64/hex methods on Uint8Array. They are available in Node.js 25 and later, and in current browsers, so they're a good choice for code that must run in both environments:
const bytes = new TextEncoder().encode('Hello');
console.log(bytes.toBase64()); // SGVsbG8=
console.log(bytes.toBase64({ alphabet: 'base64url', omitPadding: true })); // SGVsbG8
console.log(bytes.toHex()); // 48656c6c6f
const decoded = Uint8Array.fromBase64('SGVsbG8=');
console.log(new TextDecoder().decode(decoded)); // Hello
console.log(Uint8Array.fromHex('48656c6c6f')); // Uint8Array(5) [ 72, 101, 108, 108, 111 ]
Unlike Buffer.from(), these methods are strict and throw a SyntaxError on invalid input:
try {
Uint8Array.fromHex('abc'); // odd length
} catch (err) {
console.log(err.name); // SyntaxError
}
Since a Buffer is a Uint8Array subclass, buf.toHex() and buf.toBase64() also work on buffers where the engine supports them. If you need to support older Node.js versions, feature-detect:
const toHex = (bytes) =>
typeof bytes.toHex === 'function'
? bytes.toHex()
: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex');
Summary
| Task | Code |
|---|---|
| string to base64 | Buffer.from(str).toString('base64') |
| base64 to string | Buffer.from(b64, 'base64').toString() |
| URL-safe token | randomBytes(32).toString('base64url') |
| bytes to hex | buf.toString('hex') |
| hex to bytes | Buffer.from(hex, 'hex') |
| hash as hex | createHash('sha256').update(data).digest('hex') |
| decoded size | Buffer.byteLength(b64, 'base64') |
| strict decode (Node 25+) | Uint8Array.fromBase64(b64) |