Skip to content

Instantly share code, notes, and snippets.

@aroslov
Created May 21, 2019 07:04
Show Gist options
  • Save aroslov/ad6f745e512d74b128ec8fe014efeb44 to your computer and use it in GitHub Desktop.
Save aroslov/ad6f745e512d74b128ec8fe014efeb44 to your computer and use it in GitHub Desktop.
Handle CORS (OPTIONS request) in Edge Lambda for AWS CloudFront
function checkOrigin(origin) {
if (!origin) {
return false;
}
const [protocol, host, port] = origin.split(':');
// TODO: put your own logic here
if (!host) {
return false;
}
if (host === '//localhost') {
return true;
}
if (host === '//127.0.0.1') {
return true;
}
if (host === '//0.0.0.0') {
return true;
}
return false;
}
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
if (request.method === 'OPTIONS') {
const origin = headers.origin && headers.origin[0] && headers.origin[0].value;
const response = checkOrigin(origin) ? {
status: '204',
headers: {
'access-control-allow-origin':
[{ key: 'Access-Control-Allow-Origin', value: origin}],
'access-control-allow-headers': // TODO: add any other headers that your app is using
[{ key: 'Access-Control-Allow-Headers', value: 'Content-Type'}],
'access-control-allow-methods': // TODO: restrict your methods
[{ key: 'Access-Control-Allow-Methods', value: 'GET, HEAD, PUT, POST, DELETE, PATCH'}],
'access-control-allow-credentials':
[{ key: 'Access-Control-Allow-Credentials', value: 'true'}],
'access-control-max-age': // TODO: tune your expiry
[{ key: 'Access-Control-Max-Age', value: '8640000'}],
},
} : {
status: '401',
};
callback(null, response);
}
else {
callback(null, request);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment