How to do base64 encoding/decoding when using CloudFront function?
Asked Answered
S

3

5

Amazon CloudFront Function is a new feature introduced by AWS.
CloudFront Function can be written using JavaScript only.
https://aws.amazon.com/blogs/aws/introducing-cloudfront-functions-run-your-code-at-the-edge-with-low-latency-at-any-scale/

Our website generates a timestamp and encode it using btoa() (Base64 encoding).
Then, website sends HTTP GET request which includes the encoded timestamp to CloudFront function.

var sending_time        = new Date().getTime();
var enc_sending_time    = btoa(sending_time);

function generate_http_request(enc_sending_time)
{
...
}

Once CloudFront function receives the HTTP request,
it should decode the timestamp using atob().

However, CloudFront Function does not support atob(). https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-javascript-runtime-features.html

How can we do base64 encoding to an integer
and then do base64 decoding on CloudFront function side
without using btoa() and atob()? (JavaScript only)

Shocker answered 26/5, 2021 at 15:55 Comment(0)
S
3

CloudFront does not support btoa() and atob() functions,
so we cannot do Base 64 encoding/decoding using these functions.

So as an alternative, we can use the following:
https://gist.github.com/oeon/0ada0457194ebf70ec2428900ba76255

Works like a charm!

Shocker answered 28/5, 2021 at 9:49 Comment(0)
P
7

CloudFront adds a few non-standard methods, including one to string to decode from base64:

var decoded = String.bytesFrom(str, 'base64');

It also accepts base64url for encoded versions.

They show this in an example which decodes JWTs at the edge.

Unfortunately they don't seem to have the equivalent to do base64 encoding.

Party answered 7/11, 2021 at 3:48 Comment(0)
S
3

CloudFront does not support btoa() and atob() functions,
so we cannot do Base 64 encoding/decoding using these functions.

So as an alternative, we can use the following:
https://gist.github.com/oeon/0ada0457194ebf70ec2428900ba76255

Works like a charm!

Shocker answered 28/5, 2021 at 9:49 Comment(0)
C
0

The newer CloudFront Functions runtime 2.0 adds support for many Buffer methods (as you would expect in Node.js), which work for encoding/decoding Base64. See the docs for details.

Examples:

Buffer.from('Zm9vYmFy', 'base64').toString(); // returns 'foobar'
Buffer.from('foobar').toString('base64'); // returns 'Zm9vYmFy'
Cartier answered 10/5 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.