Last active
July 30, 2020 16:28
-
-
Save blackbing/6be215c1eaab33e84ab372d2dc87d8c2 to your computer and use it in GitHub Desktop.
prerender lambda@edge
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
'use strict'; | |
const https = require('https'); | |
const BASE_URL_RENDERER = 'YOUR_PRERENDER_SERVER?url='; | |
exports.handler = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
const response = event.Records[0].cf.response; | |
const headers = response.headers; | |
const SHOULD_PRERENDER = request.headers['x-should-prerender'][0].value === 'true'; | |
const PRERENDER_URL = request.headers['x-prerender-uri'][0].value; | |
if (SHOULD_PRERENDER && PRERENDER_URL) { | |
const URL = BASE_URL_RENDERER + PRERENDER_URL; | |
downloadContent(URL, (body) => { | |
callback(null, { | |
status: '200', | |
statusDescription: 'OK', | |
headers: response.headers, | |
body | |
}); | |
}); | |
} else { | |
callback(null, response); | |
} | |
}; | |
const downloadContent = function (url, callback) { | |
https | |
.get(url, function (res) { | |
var body = ''; | |
res.on('data', function (chunk) { | |
body += chunk.toString(); | |
}); | |
res.on('end', function () { | |
callback(body, null); | |
}); | |
}) | |
.on('error', function (e) { | |
callback(null, e); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment