Last active
September 28, 2022 02:31
-
-
Save karen-kua/af988c71a374672aa3e14e6873f9ca7b to your computer and use it in GitHub Desktop.
Lambda@Edge Function for Accessing React Apps in Sub-Directories of Multiple S3 Buckets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Import the data that maps the origins to each product. | |
| const bucketData = require("./bucketData.js"); | |
| exports.handler = (event, context, callback) => { | |
| // Get the request object. | |
| const request = event.Records[0].cf.request; | |
| // Get the host from the request and take out "www." from the host if it exists. | |
| let host = request.headers.host[0].value; | |
| host = host.replace(/^www\./, ""); | |
| // Parse the host to identify the product and the directory where the React app's static files are stored based on the subdomain's identifier (marketing, portal, customer, support). | |
| const [product, dir] = host.split(".")[0].split("-"); | |
| // Get the path to the directory. If the host doesn't have a subdomain with a hyphen (eg. example.com and kimchibeanz.example.com), return an empty string as the files will be at the root of the bucket. | |
| const entryPoint = dir ? `/${dir}` : ""; | |
| // Find the product in your data's list of origins. | |
| const match = bucketData.find(dataSet => product === dataSet.product); | |
| if (match) { | |
| const domain = match.origin; | |
| // If the product is in the list of origins, instruct to send the request to the matching origin, specifying for it to look for content within the sub-directory or at the root. | |
| // The key here is the 'path' property. It specifies the entry point. It does not affect the request URI (eg. /login). | |
| request.origin = { | |
| custom: { | |
| domainName: domain, | |
| port: 80, | |
| protocol: "http", | |
| path: entryPoint, | |
| sslProtocols: ["TLSv1.1", "TLSv1.2"], | |
| readTimeout: 5, | |
| keepaliveTimeout: 5, | |
| customHeaders: { | |
| // Set a referer request header to gain access to read objects in the S3 bucket. | |
| referer : [{ key: "referer", value: `http://${host}/` }] | |
| } | |
| } | |
| }; | |
| // Change the host in the request headers to match the origin's website endpoint. | |
| request.headers["host"] = [{ key: "host", value: domain }]; | |
| callback(null, request); | |
| } else { | |
| // If the product was not in the list of origins, send the request without any alterations. | |
| callback(null, request); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment