functions-samples icon indicating copy to clipboard operation
functions-samples copied to clipboard

Add Cors to callable function

Open pietrofxq opened this issue 8 years ago • 44 comments

I wrote a callable function to invite new users for my app:

exports.UserInvitation = functions.https.onCall((data, context) => {
  const email = data.email
  const password = passwordGenerator.generate({
    length: 12,
    numbers: true
  })
  console.log('Inviting user:', email)
  const mailOptions = {
    from: '',
    to: email,
    subject: ``,
    html: utils.formatEmail(`
     Hello, you've been invited to use my app.
    `)
  }

  return new Promise((resolve, reject) => {
    admin.auth().createUser({
      email: email,
      emailVerified: false,
      password: password
    }).then((user) => {
      console.log(`Created user with uid ${user.uid}`)
      transporter.sendMail(mailOptions).then(() => {
        console.log(`Email sent to ${email}`)
        resolve()
      })
    }).catch((err) => {
      console.error(err.code)
      reject(new functions.https.HttpsError(err.code, err.message))
    })
  })
})

I call it like this in my app:

functions.httpsCallable('UserInvitation')({ email: this.input.value })

But I'm getting "No Access Control Allow Origin" error when trying to call it from client. How can I fix this if I don't have access to req/res objects inside onCall, to enable cors?

pietrofxq avatar May 08 '18 15:05 pietrofxq

@pietrofxq we just added this at the top of the file: const cors = require('cors')({ origin: true }); and didn't need to change anything else.

You're probably better off on the main firebase functions github or stackoverflow for stuff like this 😉

ahaverty avatar May 17 '18 14:05 ahaverty

If you're using Firebase hosting, you can use a rewrite to move your functions onto the same domain as the rest of your site: https://firebase.google.com/docs/hosting/functions#direct_hosting_requests_to_your_function

(This means requests will no longer be cross-origin, and won't trigger CORS)

SidneyNemzer avatar May 17 '18 18:05 SidneyNemzer

I was able to solve the issue. There's no way to add CORS to onCall functions because it's handled automatically. The problem was with my error handler: when returning an instance of functions.https.HttpsError, the first parameter MUST match one of the codes listed in this page: https://firebase.google.com/docs/reference/functions/functions.https.HttpsError

pietrofxq avatar May 17 '18 21:05 pietrofxq

@pietrofxq but the error message is not been sent. or?

HelmerBarcos avatar Aug 25 '18 20:08 HelmerBarcos

@pietrofxq Just wanted to thank you personally, I had the same issue and was pulling my hair out. Really not intuitive

jshaker avatar Oct 16 '18 02:10 jshaker

This can happen whenever there is an error in the function. In my case I was passing an undefined variable to the callable function

8tomo8 avatar Nov 18 '18 23:11 8tomo8

I am having the same issue.

My Firebase client is 5.8.2 My Firebase Cloud Function are: admin 7.0.0, and functions 2.2.0

My client code:

const someFunction = FirebaseFunctions.httpsCallable("someFunction");
someFunction({  email: "[email protected]"  })
.then(result => {
  console.log("someFunction response: ", result.data);
}).catch(error => {
   console.log("error",error);
});

My Cloud Functions code:

const functions = require("firebase-functions");
...
exports.someFunction = functions.https.onCall((data) => {

    return {
        email: data.email
    };
});

As you can see, all I am really doing for a simple test is trying to return the email back to the client, but I am getting blocked by CORS. It does not matter if I run from localhost or I deploy the client to Firebase Hosting, the result is the same.

Does anybody know what I am doing wrong?

tricaricom avatar Feb 05 '19 05:02 tricaricom

@tricaricom Did you ever solve this? I'm having the same issue.

nicholmikey avatar May 27 '19 00:05 nicholmikey

@nicholmikey no I never did get it to work. I used the cors method mentioned above and it works. I would like to get callable functions to work at some point though.

tricaricom avatar May 29 '19 02:05 tricaricom

@tricaricom @nicholmikey The CORS error in console with callable functions only indicates there is an error in the cloud function. Check the logs inside the Firebase console and you'll see the actual error. CORS is not applicable for callable functions even when running on localhost

8tomo8 avatar May 29 '19 05:05 8tomo8

I have the same issue... Stuck since 2hours.. :-(

gregbkr avatar Jun 14 '19 12:06 gregbkr

Same issue - Even stranger, I have 2 functions, both exactly the same (both are essentially empty), both a direct callables (onCall) and one of them gives a CORS error, the other not (I posted the question to reddit as well: https://www.reddit.com/r/Firebase/comments/c4js7u/cors_issue_with_one_cloud_function_but_not/)

Here is the code

// cloud functions
const functions = require('firebase-functions');
const REGION = 'europe-west1';
exports.workingFunctions = functions.region(REGION).https.onCall((data, context) => {
 console.log('workingFunctions');
 return {
  a: 1
 };
});
exports.notWorkingFunction = functions.region(REGION).https.onCall((data, context) => {
 console.log('notWorkingFunction');
 return {
  b: 2
 };
});

// webapp
export async function test() {
 console.log('1');
 let workingFunctionAPI = functions.httpsCallable("workingFunction"); workingFunctionAPI().then(result => {
  console.log('workingFunctionAPI', result)
 }).catch(err => {
  console.error('workingFunctionAPI', err);
 });

 console.log('2');
 let notWorkingFunctionAPI = functions.httpsCallable("notWorkingFunction"); notWorkingFunctionAPI().then(result => {
  console.log('notWorkingFunctionAPI', result)
 }).catch(err => {
  console.error('notWorkingFunctionAPI', err);
 }); console.log('3');
}

Another weird thing is that I had another firebase project, where I think that everything is exactly the same, but there both of these functions were working without any issues. When I deployed the same code to this project (this project is stage, the other was dev), one function is failing

xximranxx avatar Jun 24 '19 08:06 xximranxx

Also, how can we reopen the issue?

xximranxx avatar Jun 24 '19 08:06 xximranxx

@xximranxx : After searching hours... I fixed my problem. Probably same as yours:

  • By default, firebase serve sends your queries to CLOUD function, so strange!!!….. Means you think you are testing locally v10, but no, only html v10 is local and you are really testing function v0.2 which is in the cloud… :-0

  • Seems like something is missing in the firebase doc or the way how firebase works… CORS is exactly a result of that behaviour (html localhost:5000 calling cloud function https://myproject.firebase.com/myapp).

  • Now I deleted my app "helloWorld" in the cloud.

  • Added : firebase.functions().useFunctionsEmulator('http://localhost:5001') <script> section of index.html, so local html is targeting my LOCAL functions.

  • And no more CORS error… :-))

Thread of similar error: https://stackoverflow.com/questions/51139843/firebase-serve-from-a-locally-served-app-call-locally-served-functions

Still you will need to comment the line before to push in cloud. But cloud html + cloud function do not give me any CORS error.

My code if it could help: https://gitlab.com/finstack/search-hack-db/tree/master/firebase-simple-function

Hope it will fix you! See you!

gregbkr avatar Jun 24 '19 08:06 gregbkr

@gregbkr My issue is also for cloud html + cloud function, not only when testing locally In that case, I don't see anything at all that is different in yours

xximranxx avatar Jun 24 '19 08:06 xximranxx

  • Yes, I could not make html + cloud works in beginning too.
  • When I fixed locally it all works fine. I saw sometimes CORS errors because of bad syntaxes or parameters for function oncall().
  • Try my exact code locally to see if it helps.

gregbkr avatar Jun 24 '19 08:06 gregbkr

@gregbkr I tried - If I use the local emulator, everything worked perfectly immediately; no CORS issue So it's only on the cloud

Any ideas, anyone?

xximranxx avatar Jun 24 '19 12:06 xximranxx

I seemed to have gotten it to work by

  1. Deleting the (web) app from the firebase console
  2. Deleting the cloud functions and deploy them again Not sure which step was responsible

Can I trust that it will work from now? Not sure, as I have no idea what was causing it and whether CORS is supposed to be an issue or not. I would say not, onCall should take care of that

xximranxx avatar Jun 24 '19 12:06 xximranxx

I think this happens when trying to evoke functions.https.onCall from hosting/ports other than the firebase serve env. I was trying to call from react-scripts start env.

chris-gunawardena avatar Aug 19 '19 13:08 chris-gunawardena

Hello everyone, in my app, I first added firebase.functions().useFunctionsEmulator('http://localhost:5000'); after firebase.initializeApp() to test my callable functions locally. I had the the CORS error on when trying to call them with my app locally. By changing to firebase.functions().useFunctionsEmulator('http://localhost:5001');, it worked for me.

CaptainYouz avatar Aug 24 '19 08:08 CaptainYouz