Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Last active December 27, 2018 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/5abf88b4ce6b45e914be8cdd38281f54 to your computer and use it in GitHub Desktop.
Save ritwickdey/5abf88b4ce6b45e914be8cdd38281f54 to your computer and use it in GitHub Desktop.
CORS Middleware (Higher Order Function) for firebase function // Just Nice Syntax
//For firebase funtion.
/*
Usage:
exports.foo = functions.https.onRequest(withCORS((req, res) => {
res.send("Hello World");
});
*/
const withCORS = next => (req, res) => {
res.header('Access-Control-Allow-Origin', '*'); // Allowed Origins.
res.header('Access-Control-Allow-Headers', '*'); // Allowed Headers.
res.header('Access-Control-Expose-Headers', 'token'); // Exposed Headers - means client only can access those headers.
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE'); // Allowed Methods.
res.header('Access-Control-Max-Age', 5 * 24 * 60 * 60); //5 days... But Chrome will take its MAX value. :D
return res.status(200).json({});
}
next(req, res);
};
module.exports = { withCORS };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment