Base64 Encode & Decode in Node.js

Encode or decode below — it runs locally in your browser — then grab the canonical Node.js code. Node's built-in Buffer is the idiomatic way: Buffer.from(str).toString('base64') to encode and Buffer.from(b64, 'base64').toString('utf8') to decode, no packages needed.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

The key pattern is Buffer.from(str) → toString('base64'), then reverse it with the 'base64' input encoding:

// Encode
const encoded = Buffer.from('Hello, world!').toString('base64');
console.log(encoded); // "SGVsbG8sIHdvcmxkIQ=="

// Decode
const decoded = Buffer.from(encoded, 'base64').toString('utf8');
console.log(decoded); // "Hello, world!"

Tip: Buffer is the idiomatic Node way — no btoa() needed. btoa()/atob() do exist as globals in Node 16+, but Buffer.from(str) defaults to UTF-8 so emoji and non-ASCII text just work.

URL-safe Base64

For JWTs, URLs, and filenames, use the 'base64url' encoding (Node 14.18+) — it swaps +// for -/_ and drops padding:

// URL-safe encode (no +, /, or = characters)
const encoded = Buffer.from('Hello, world!').toString('base64url');
console.log(encoded); // "SGVsbG8sIHdvcmxkIQ"

// Decode base64url back to text
const decoded = Buffer.from(encoded, 'base64url').toString('utf8');
console.log(decoded); // "Hello, world!"

Encode a file / streams

const fs = require('fs');

// Encode a file to a Base64 string
const encoded = fs.readFileSync('image.png').toString('base64');

// As a data URI for HTML/CSS:
const dataUri = `data:image/png;base64,${encoded}`;

// Decode Base64 back to a file
fs.writeFileSync('output.png', Buffer.from(encoded, 'base64'));

Frequently asked questions

How do I Base64 encode a string in Node.js?

Buffer.from('Hello, world!').toString('base64') returns "SGVsbG8sIHdvcmxkIQ==". Buffer is a global, so no import or package is needed.

How do I Base64 decode in Node.js?

Buffer.from('SGVsbG8sIHdvcmxkIQ==', 'base64').toString('utf8') returns "Hello, world!"; omit 'utf8' for a raw byte Buffer.

How do I do URL-safe Base64?

Use the 'base64url' encoding (Node 14.18+): Buffer.from(data).toString('base64url'), and Buffer.from(str, 'base64url') to decode.

Should I use Buffer or btoa() in Node.js?

Use Buffer. btoa() exists in Node 16+ but shares the browser's Unicode limitation, while Buffer.from(str) defaults to UTF-8.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →