Use key-value pairs in a function - Amazon CloudFront

Use key-value pairs in a function

You can use key-value pairs from a key value store in a function.

Note

You must use JavaScript runtime 2.0 for the following code sample.

The example shows a function that uses the content of the URL in the HTTP request to look up a custom path in the key value store. CloudFront then uses that custom path to make the request. This function helps manage the multiple paths that are part of a website.

import cf from 'cloudfront'; ​ // Declare the ID of the key value store that you have associated with this function // The import fails at runtime if the specified key value store is not associated with the function const kvsId = "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"; ​ const kvsHandle = cf.kvs(kvsId); ​ async function handler(event) { const request = event.request; // Use the first segment of the pathname as key // For example http(s)://domain/<key>/something/else const pathSegments = request.uri.split('/') const key = pathSegments[1] try { // Replace the first path of the pathname with the value of the key // For example http(s)://domain/<value>/something/else pathSegments[1] = await kvsHandle.get(key); const newUri = pathSegments.join('/'); console.log(`${request.uri} -> ${newUri}`) request.uri = newUri; } catch (err) { // No change to the pathname if the key is not found console.log(`${request.uri} | ${err}`); } return request; }