How does firebase authentication work with ionic and capacitor?


When the app is launching for the sign in page, an error is occurring that relates to the authorized domains:
Cross-origin redirection to denied by Cross-Origin Resource Sharing policy: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin. Status code: 301

When I try to add capacitor://localhost to the list of authorized domains, it throws the error A valid domain name is required (e.g. '')

My authentication code both has a listener:

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (userInfo) => {
      if (userInfo === null) {
      } else {
        const token = await userInfo.getIdToken(true);
        localStorage.setItem("AuthToken", `Bearer ${token}`);
    return unsubscribe;
  }, [user, history]);

and the sign in function:

export const signIn = async (email, password) => {
  try {
    await setPersistence(auth, browserLocalPersistence);
    const userCredential = await signInWithEmailAndPassword(

    const user = userCredential.user;
    const token = await user.getIdToken(true);
    localStorage.setItem("AuthToken", `Bearer ${token}`);
    return { user, token };
  } catch (error) {
    return { error: error.message };

I have seen some answers that might suggest it has to do with the Firebase Auth SDK having issues with capacitor because it is meant for a web app instead of mobile apps. However, there has not been very clear answers as to how I can confirm if that is the problem or how to solve it.


The solution was to implement this when using the firebase auth object

function whichAuth() {
  let auth;
  if (Capacitor.isNativePlatform()) {
    auth = initializeAuth(app, {
      persistence: indexedDBLocalPersistence,
  } else {
    auth = getAuth(app);
  return auth;

export const auth = whichAuth();

Answered By – Kasey Kaufmann

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published