documents/dev/snippets/aws/CloudFront functions.md

Cloudfront Functions

https://github.com/aws-samples/amazon-cloudfront-functions

Basic Usage

function handler(event) {
  var request = event.request;
  var uri = request.uri;
  
  if(uri == '/about' || uri.match(/^\/file\//)) {
    request.uri = '/index.html';
  }
  
  request.uri = uri.replace(/\/$/, '/index.html');
  
  return request;
}

Redirect

function handler(event) {
  var request = event.request;
  var uri = request.uri;
  if(uri == '/support') {
    return {
        statusCode: 301,
        statusDescription: 'Moved Permanently',
        headers: {
            'location': { value: 'https://github.com/EnotionZ/flowdown/issues' }
        }
    };
  }
}

Sample Request

Sample event.request: https://flowdown.dph.am/evt/abc?q=1#/path Note: hash doesn't appear, queryString gets parsed

{
  "method": "GET",
  "uri": "/evt/abc",
  "querystring": {
    "q": { "value": "1" }
  },
  "headers": {
    "user-agent": { "value": "Mozilla/5.0 (X11; CrOS x86_64 14268.67.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.111 Safari/537.36" },
    "sec-ch-ua-mobile": { "value": "?0" },
    "cache-control": { "value": "no-cache" },
    "host": { "value": "flowdown.dph.am" },
    "accept": { "value": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" },
    "upgrade-insecure-requests": { "value": "1" },
    "sec-fetch-site": { "value": "none" },
    "sec-fetch-dest": { "value": "document" },
    "accept-language": { "value": "en-US,en;q=0.9,vi-VN;q=0.8,vi;q=0.7,da;q=0.6" },
    "dnt": { "value": "1" },
    "accept-encoding": { "value": "gzip, deflate, br" },
    "pragma": { "value": "no-cache" },
    "sec-ch-ua-platform": { "value": "\"Chrome OS\"" },
    "sec-fetch-user": { "value": "?1" },
    "sec-ch-ua": { "value": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"" },
    "sec-fetch-mode": { "value": "navigate" }
  },
  "cookies": {
    "G_ENABLED_IDPS": { "value": "google" },
    "G_AUTHUSER_H": { "value": "0" }
  }
}