Skip to content

Instantly share code, notes, and snippets.

@furkan3ayraktar
Last active October 5, 2023 16:38
Show Gist options
  • Save furkan3ayraktar/2ba5e34985addc4107dc417399be2b9d to your computer and use it in GitHub Desktop.
Save furkan3ayraktar/2ba5e34985addc4107dc417399be2b9d to your computer and use it in GitHub Desktop.
Complete Lambda@Edge function to inject metadata.
const path = require('path');
const https = require('https');
const zlib = require('zlib');
const downloadContent = (url, callback) => {
https.get(url, (res) => {
let response;
let body = '';
if (res.headers['content-encoding'] === 'gzip') {
response = res.pipe(zlib.createGunzip());
} else {
response = res;
}
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
callback(true, body, res.headers);
});
}).on('error', (e) => callback(false, e));
};
const fetchMetaData = (url, callback) => {
downloadContent(url, (isOk, result, headers) => {
if (!isOk) {
console.log('Error fetching meta data:', result);
callback(false);
} else {
const metaData = JSON.parse(result);
let metaTags = '';
if (metaData) {
if (metaData.title) {
metaTags += '<title>' + metaData.title + '</title>';
metaTags += '<meta property=\"og:title\" content=\"' + metaData.title + '\" />';
}
if (metaData.description) {
metaTags += '<meta name=\"description\" content=\"' + metaData.description + '\" />';
metaTags += '<meta property=\"og:description\" content=\"' + metaData.description + '\" />';
}
if (metaData.images) {
for (let i = 0; i < metaData.images.length; i++) {
const image = metaData.images[i];
metaTags += '<meta property=\"og:image\" content=\"' + image + '\" />';
}
}
}
metaTags += '<meta property=\"og:url\" content=\"https://' + domainName + originalUri + '\" />';
metaTags += '<meta property=\"og:type\" content=\"website\" />';
callback(true, metaTags, headers);
}
});
};
const fetchIndexHtmlAndCreateCloudFrontResponse = (url, metaTags, metaHeaders, callback) => {
downloadContent(url, (isOk, result, headers) => {
if (!isOk) {
console.log('Error fetching content:', result);
callback(false);
} else {
// We have <title>House of Radon</title> inside the actual index.html. We use that part to replace with actual metadata.
const finalBody = result.replace('<title>House of Radon</title>', metaTags);
const buffer = zlib.gzipSync(finalBody);
const base64EncodedBody = buffer.toString('base64');
const responseHeaders = {
'content-type': [{key:'Content-Type', value: 'text/html'}],
'content-encoding' : [{key:'Content-Encoding', value: 'gzip'}],
'accept-ranges': [{key:'Accept-Ranges', value: 'bytes'}]
};
let eTag = '';
if (metaHeaders) {
const metaEtag = metaHeaders['etag'];
if (metaEtag) {
eTag = metaEtag.replace(/"/g, '');
}
}
if (headers) {
const lastModified = headers['last-modified'];
const cacheControl = headers['cache-control'];
const contentETag = headers['etag'];
if (lastModified) {
responseHeaders['last-modified'] = [{key:'Last-Modified', value: lastModified}]
}
if (cacheControl) {
responseHeaders['cache-control'] = [{key:'Cache-Control', value: cacheControl}]
}
if (contentETag) {
eTag += contentETag.replace(/"/g, '');;
}
}
if (eTag !== '') {
responseHeaders['etag'] = [{key:'ETag', value: eTag}]
}
const newResponse = {
status: '200',
statusDescription: 'OK',
headers: responseHeaders,
body: base64EncodedBody,
bodyEncoding: 'base64',
};
callback(true, newResponse);
}
});
};
exports.handler = (event, context, callback) => {
const { request, config } = event.Records[0].cf;
let originalUri = request.uri;
const parsedPath = path.parse(originalUri);
if (parsedPath.ext === '') {
request.uri = '/index.html';
let metaUrl = 'https://houseofradon.com';
if (parsedPath.dir === '/') {
metaUrl += '/api/meta?type=' + parsedPath.base;
} else if (parsedPath.dir === '/creative' || parsedPath.dir === '/venture') {
metaUrl += '/api/case/' + parsedPath.base + '/meta';
} else if (parsedPath.dir === '/join-us') {
metaUrl += '/api/career/' + parsedPath.base + '/meta';
} else {
metaUrl += '/api/meta?type=';
}
fetchMetaData(metaUrl, (isOk, metaTags, metaHeaders) => {
if (!isOk) {
return callback(null, request); // Return same request so CloudFront can process as usual.
} else {
const contentUrl = 'https://houseofradon.com/index.html';
fetchIndexHtmlAndCreateCloudFrontResponse(contentUrl, metaTags, metaHeaders, (isOk, newResponse) => {
if (!isOk) {
return callback(null, request);
} else {
return callback(null, newResponse);
}
});
}
});
} else {
return callback(null, request);
}
};
@JacksonBates
Copy link

Thanks for this!

This served as a pretty solid foundation for what I was trying to do.

btw I think line 102 should be:

  if (cacheControl) {

@furkan3ayraktar
Copy link
Author

Thanks for the heads up! I'll update it right away!

@ashleygwinnell
Copy link

Hi - thanks for sharing! Do you specify this as the lambda for origin-response, origin-request or something else?

@JacksonBates
Copy link

@ashleygwinnell I do it in the origin-request.

@furkan3ayraktar
Copy link
Author

Yes, it is specified as Origin Request.

@dmitryame
Copy link

can we get some sample code how to configure this function in CDK stack?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment