-
-
Save mediavrog/49c4f809dffea4e00738a7f5e3bbfa59 to your computer and use it in GitHub Desktop.
const cors = require('cors')({origin: true}); | |
exports.sample = functions.https.onRequest((req, res) => { | |
cors(req, res, () => { | |
res.send('Passed.'); | |
}); | |
}); |
Here's my solution:
middleware.ts
import * as functions from 'firebase-functions';
import { corsMiddleware } from './cors';
export type FunctionHandler = (
req: functions.https.Request,
res: functions.Response<any>,
) => void | Promise<void>;
export const withMiddleware = (
handler: FunctionHandler,
regions = ['europe-west2', 'europe-west3'],
) =>
functions.region(...regions).https.onRequest((req, res) => {
return corsMiddleware(req, res, () => {
handler(req, res);
});
});
and you can use it like so:
export const sendContactMessage = withMiddleware(async (req, res) => {
});
@jesster2k10 Your answer seems great, but passing the regions with the spread operator gives an typescript error.
Argument of type 'string' is not assignable to parameter of type '"europe-west2" | "europe-west3" | "us-central1" | "us-east1" | "us-east4" | "europe-west1" | "asia-east2" | "asia-northeast1"'.ts(2345)
.
Do you know how to fix this? For now I'm sticking to one region to overcome this problem.
Thanks for the great answer.
@jpfong I want to thank you for your post I have been spending the last 4 hours trying to get cors working. So random why would they not put an example in the docs. Thank you so much
Hello, Im getting the cors error and I can figure out why, here is may code:
import express from "express";
import cors from "cors";
const expressApp = express();
expressApp.use(cors({origin: true}));
expressApp.get("/Hello", (req, res) => {
res.send("Hello!");
});
Can anyone help me out?
// Enable CORS using the
cors
express middleware.return cors(req, res, () => {
// ...
});
It is there in documentations but not for callable functions, Firebase should have been more clear with the documentation.
Thanks you.