Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cheapsteak/dfbec27ab7c5e7d74816272dfeae7352 to your computer and use it in GitHub Desktop.
Save cheapsteak/dfbec27ab7c5e7d74816272dfeae7352 to your computer and use it in GitHub Desktop.
const netlifyHost = 'my-app.netlify.app';
const shouldAllowCORS = (origin) => {
if (/http\:\/\/localhost:/.test(origin)) {
return true;
}
if (origin === (`https://${netlifyHost}`) || (new RegExp(`--${netlifyHost.replace(/\./g, '\.')}`)).test(origin)) {
return true;
}
return false;
}
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.myHandler = (req, res) => {
const origin = req.headers.origin;
if (shouldAllowCORS(origin)) {
res.set('Access-Control-Allow-Origin', origin);
if (req.method === 'OPTIONS') {
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', '*');
res.status(204).send('');
return;
}
}
// ... rest of handler
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment