This article describes how to encode / decode Base64URL with Node.js. The related resources are shown below.
The workflow is shown below.
- Coding preparation
- Coding
- Operation check
Run the following commands in your terminal to prepare for coding.
mkdir nodejs-base64url-encode
cd nodejs-base64url-encode
npm init -y
touch main.js
Open main.js in your editor and enter the following content.
The points are shown below.
- The encodeBase64Url function replaces "+" with "-", "/" with "_", and removes =.
- The decodeBase64Url function first replaces "-" with "+" and "_" with "/". Then use the Buffer.from function to convert the Base64 string to Buffer.
Run the following command in your terminal and check that original and decoded match.
node main.js
The execution result is shown below.
{ original: 'ま', encoded: '44G-', decoded: 'ま' }
You can also check using Base64 Guru's Base64URL Decode.
Base64URL-encoded strings can be included in URLs and filenames without escaping, which is useful when you want to convert a random byte string to a shorter string. As an example, it is used in OAuth 2.0's Authorization Code Grant with PKCE. In this article, I implemented it myself for learning, but there are also npm packages like base64url. So when I don't have the energy to implement Base64URL encoding, I would like to use it.
Hex (hexadecimal) encoding (eg e381be for "ま") can be included in URLs and filenames as well as Base64URL, but will be longer than Base64URL. However, long is not bad. Hex has an advantage that it is easier to understand because 2 characters correspond to 1 byte. Hashes such as Git commits and SHA256 checksums are often displayed in Hex.
It was a simple theme, so coding was done quickly. However, it took a long time because it was difficult to find a character that contains "-" in the result of Base64URL encoding. If you know of a nice test string to test Base64URL encoding, i would appreciate your guidance comments. Thank you for reading!