Skip to content

Instantly share code, notes, and snippets.

@hoegertn
Last active December 23, 2021 03:16
Show Gist options
  • Save hoegertn/13b6b8c3adfeab1168326345ded4938f to your computer and use it in GitHub Desktop.
Save hoegertn/13b6b8c3adfeab1168326345ded4938f to your computer and use it in GitHub Desktop.
Rich Social Sharing with CloudFront
exports.handler = (event, context, callback) => {
'use strict';
const request = event.Records[0].cf.request;
const userAgent = request.headers['user-agent'][0].value;
let prerender = 0;
// user agent is known social bot
if (userAgent.match(/baiduspider|twitterbot|facebookexternalhit|googlebot|bingbot|yandex|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator/i)) {
prerender = 1;
}
// rendered page is requested by special query string
if (request.querystring.match(/_escaped_fragment_/)) {
prerender = 1;
}
// request is coming from prerender.io, so serve original page
if (userAgent.match(/Prerender/)) {
prerender = 0;
}
// request targets non-html files
if (request.uri.match(/\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)/i)) {
prerender = 0;
}
if (prerender === 1) {
request.origin = {
custom: {
protocol: 'http',
domainName: 'service.prerender.io',
port: 80,
path: '/https://www.example.de',
sslProtocols: ['TLSv1', 'TLSv1.1'],
readTimeout: 30,
keepaliveTimeout: 30,
customHeaders: {
'x-prerender-token': [
{
"key": "X-Prerender-Token",
"value": "yourPrerenderIOToken"
}
]
}
}
};
}
callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment