DEV Community

Colby Hemond
Colby Hemond

Posted on

3 3

Encoding/Decoding Base64 with Node.js Core Buffer API

The Node.js core Buffer API allows base64 encoding for cases like Basic authentication.

The legacy version with Node.js is by using the buf.atob() and buf.btoa() methods, and according to their documentation should not be used in new code.

So here's the recommended way...

Encoding a string to base64

const user = 'colbyhemond'
const password = 'test123!@#'
const stringBuffer = Buffer.from(`${user}:${password}`)
const stringBase64 = stringBuffer.toString('base64')

console.log(stringBase64)
// will output: "Y29sYnloZW1vbmQ6dGVzdDEyMyFAIw=="
Enter fullscreen mode Exit fullscreen mode

Decoding from base64 to a unicode string

const base64String = 'Y29sYnloZW1vbmQ6dGVzdDEyMyFAIw=='
const base64Buffer = Buffer.from(base64String, 'base64')
const string =  base64Buffer.toString()

console.log(string)
// will output: "colbyhemond:test123!@#"
Enter fullscreen mode Exit fullscreen mode

To see how you can turn this into your own encoding utility and publish it on NPM, checkout the post on my website.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more