Skip to content

Instantly share code, notes, and snippets.

@ritwickdey

ritwickdey/withCORS.js

Last active Dec 27, 2018
Embed
What would you like to do?
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