Skip to content

@firebase/auth: Auth (10.1.0): INTERNAL ASSERTION FAILED: Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill #7533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rzych112 opened this issue Aug 7, 2023 · 10 comments · Fixed by #7634

Comments

@rzych112
Copy link

rzych112 commented Aug 7, 2023

Operating System

Ubuntu 16

Browser Version

Chrome 114 on Linux

Firebase SDK Version

10.1

Firebase SDK Product:

Auth

Describe your project's tooling

Vite app

Describe the problem

Hello, I'm having trouble authenticating to firebase only on production build. In the skin: the built Vite application does not fire immediately, but provides a 'load' script, which includes the 'start' method - this script is loaded in another application and there the 'start' method is fired and the application is initialized. So main Vite file doing something like this:

const start = async (): Promise<void> => {
  const app = createApp(App);
  const firebaseApp = initializeApp({
    apiKey: '...',
    authDomain: '...',
    projectId: '...',
    storageBucket: '...',
    messagingSenderId: '...',
    appId: '...'
  });

  await signInWithCustomToken(getAuth(), myCustomToken);

  app.use(VueFire, { firebaseApp, modules: [VueFireAuth()] });
  app.use(BootstrapVue3);
  app.use(store);
  app.mount('#main');
};

if (window) {
  window.start = start;
}

window.addEventListener('DOMContentLoaded', (event) => {
  window.start = start;
});

If I run this app by npm start and i the web console type window.start(); everything is fine. Init ok, connect to the firebase - ok

If I build the application and upload it to firebase hosting with this configuration.

{
  "hosting": {
    "site": "my-app",
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [ {
      "source": "**",
      "headers": [
        {
          "key": "Access-Control-Allow-Origin",
          "value": "*"
        },
        {
          "key": "Cache-Control",
          "value": "max-age=7200"
        }
    ]
    } ]
  }
}

I'll get a link to it: https://my-app.web.app When I go to the link, fire the start method through the console as above - still, everything is ok.

But when my other application adds this script to itself and tries to initialize it there I get errors, caused by the 'signInWithCustomToken' method. Do you have any ideas on how to investigate more at all?

Steps and code to reproduce issue

@firebase/auth: Auth (10.1.0): INTERNAL ASSERTION FAILED: Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill

Uncaught (in promise) FirebaseError: Firebase: Error (auth/network-request-failed).
    at I4 (vendor-6cc30cfd.js:521:339)
    at Ee (vendor-6cc30cfd.js:521:30)
    at ZT (vendor-6cc30cfd.js:626:1258)
    at async PT (vendor-6cc30cfd.js:626:1350)
    at async Hk (vendor-6cc30cfd.js:1121:43)

at I4 (vendor-6cc30cfd.js:521:339):

function I4(t, ...M) {
    if (typeof t != "string") {
        const i = M[0]
          , e = [...M.slice(1)];
        return e[0] && (e[0].appName = t.name),
        t._errorFactory.create(i, ...e) // <--------------
    }
    return JT.create(t, ...M)
}

at Ee (vendor-6cc30cfd.js:521:30)

function I4(t, ...M) {
    if (typeof t != "string") {
        const i = M[0]
          , e = [...M.slice(1)];
        return e[0] && (e[0].appName = t.name),
        t._errorFactory.create(i, ...e) // <--------------
    }
    return JT.create(t, ...M)
}

at ZT (vendor-6cc30cfd.js:626:1258)

async function ZT(t, M, i) {
    t._canInitEmulator = !1;
    const e = Object.assign(Object.assign({}, g3), M);
    try {
        const I = new j3(t)
          , D = await Promise.race([i(), I.promise]);
        I.clearNetworkTimeout();
        const A = await D.json();
        if ("needConfirmation"in A)
            throw AN(t, "account-exists-with-different-credential", A);
        if (D.ok && !("errorMessage"in A))
            return A;
        {
            const u = D.ok ? A.errorMessage : A.error.message
              , [N,g] = u.split(" : ");
            if (N === "FEDERATED_USER_ID_ALREADY_LINKED")
                throw AN(t, "credential-already-in-use", A);
            if (N === "EMAIL_EXISTS")
                throw AN(t, "email-already-in-use", A);
            if (N === "USER_DISABLED")
                throw AN(t, "user-disabled", A);
            const L = e[N] || N.toLowerCase().replace(/[_\s]+/g, "-");
            if (g)
                throw D3(t, L, g);
            Ee(t, L)
        }
    } catch (I) {
        if (I instanceof Ie)
            throw I;
        Ee(t, "network-request-failed", { // <--------------
            message: String(I)
        })
    }
}

at async PT (vendor-6cc30cfd.js:626:1350)

async function PT(t, M, i, e, I={}) {
    const D = await hu(t, M, i, e, I); // <--------------
    return "mfaPendingCredential"in D && Ee(t, "multi-factor-auth-required", {
        _serverResponse: D
    }),
    D
}

at async Hk (vendor-6cc30cfd.js:1121:43)

async function Hk(t, M) {
    const i = zu(t)
      , e = await Z3(i, { // <--------------
        token: M,
        returnSecureToken: !0
    })
      , I = await JI._fromIdTokenResponse(i, "signIn", e);
    return await i._updateCurrentUser(I.user),
    I
}
@rzych112 rzych112 added new A new issue that hasn't be categoirzed as question, bug or feature request question labels Aug 7, 2023
@jbalidiong jbalidiong added needs-attention and removed new A new issue that hasn't be categoirzed as question, bug or feature request labels Aug 7, 2023
@rzych112
Copy link
Author

rzych112 commented Aug 8, 2023

Okay - in FetchProvider, method fetch

  static fetch() {
    if (this.fetchImpl) {
      return this.fetchImpl;
    }
    if (typeof self !== "undefined" && "fetch" in self) {
      return self.fetch;
    }
    debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill");
  }

I don't have this.fetchImpl I didn't initialize FetchProvider manually. On the hosting self is a Window object (and it has fetch method) But in my app this is a object like this:

lastTime: 0
setTimeout: ƒ (fn, time, thisArg)
throttle: ƒ (fn, timer, context)
ticker: Ticker {_emitter: EventEmitter, _requestId: 2701, _maxElapsedMS: 100, autoStart: true, _tick: ƒ, …}
timeout: ƒ (fn, time, thisArg)

And there is no fetch method. That's why this is not working.
What will be the best solution? Manually initializing the FetchProvider, changing the self object?

@rzych112
Copy link
Author

rzych112 commented Aug 8, 2023

Why does it only consider the object 'self' and not 'self' or 'window'?

@Xiaoshouzi-gh
Copy link

Can you provide more detail on your Vite application environment? Is this for server side rendering?

@google-oss-bot
Copy link
Contributor

Hey @rzych112. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

@soyaaroncervantes
Copy link

I'm getting the same error, I'm working with Turborepo.
I'm trying to implement Firebase Auth to my library, and when I was testing my function, it threw this error.

This is my function

import { Auth, signInWithCustomToken } from 'firebase/auth';

export const customToken = async (auth: Auth, customToken: string) => {
  const token = customToken.trim();
  if (token.length === 0) await Promise.reject(new Error('Token is empty'));
  return await signInWithCustomToken(auth, token);
};

and this is what I got on my console

console.error
    [2023-08-24T00:40:52.023Z]  @firebase/auth: Auth (10.3.0): INTERNAL ASSERTION FAILED: Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill

      at Logger.defaultLogHandler [as _logHandler] (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:115:57)
      at Logger.Object.<anonymous>.Logger.error (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:210:5)
      at _logError (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/log.ts:48:15)
      at debugFail (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/assert.ts:265:3)
      at Function.fetch (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/fetch_provider.ts:46:5)
      at ../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:137:26
      at _performFetchWithErrorHandling (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:158:32)
      at _performSignInRequest (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:217:27)
      at signInWithCustomToken (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:47:37)

Please let me know how I can help you

@romainjacquel
Copy link

romainjacquel commented Aug 27, 2023

I'm getting the same error, I'm working with Turborepo. I'm trying to implement Firebase Auth to my library, and when I was testing my function, it threw this error.

This is my function

import { Auth, signInWithCustomToken } from 'firebase/auth';

export const customToken = async (auth: Auth, customToken: string) => {
  const token = customToken.trim();
  if (token.length === 0) await Promise.reject(new Error('Token is empty'));
  return await signInWithCustomToken(auth, token);
};

and this is what I got on my console

console.error
    [2023-08-24T00:40:52.023Z]  @firebase/auth: Auth (10.3.0): INTERNAL ASSERTION FAILED: Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill

      at Logger.defaultLogHandler [as _logHandler] (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:115:57)
      at Logger.Object.<anonymous>.Logger.error (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:210:5)
      at _logError (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/log.ts:48:15)
      at debugFail (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/assert.ts:265:3)
      at Function.fetch (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/fetch_provider.ts:46:5)
      at ../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:137:26
      at _performFetchWithErrorHandling (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:158:32)
      at _performSignInRequest (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:217:27)
      at signInWithCustomToken (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:47:37)

Please let me know how I can help you

I have the same issue, have you fix that ? :)

@soyaaroncervantes
Copy link

soyaaroncervantes commented Aug 28, 2023

I'm getting the same error, I'm working with Turborepo. I'm trying to implement Firebase Auth to my library, and when I was testing my function, it threw this error.
This is my function

import { Auth, signInWithCustomToken } from 'firebase/auth';

export const customToken = async (auth: Auth, customToken: string) => {
  const token = customToken.trim();
  if (token.length === 0) await Promise.reject(new Error('Token is empty'));
  return await signInWithCustomToken(auth, token);
};

and this is what I got on my console

console.error
    [2023-08-24T00:40:52.023Z]  @firebase/auth: Auth (10.3.0): INTERNAL ASSERTION FAILED: Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill

      at Logger.defaultLogHandler [as _logHandler] (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:115:57)
      at Logger.Object.<anonymous>.Logger.error (../../node_modules/.pnpm/@firebase+logger@0.4.0/node_modules/@firebase/logger/src/logger.ts:210:5)
      at _logError (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/log.ts:48:15)
      at debugFail (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/assert.ts:265:3)
      at Function.fetch (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/util/fetch_provider.ts:46:5)
      at ../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:137:26
      at _performFetchWithErrorHandling (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:158:32)
      at _performSignInRequest (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/api/index.ts:217:27)
      at signInWithCustomToken (../../node_modules/.pnpm/@firebase+auth@1.3.0_@firebase+app@0.9.17/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:47:37)

Please let me know how I can help you

I have the same issue, have you fix that ? :)

Yes, I followed this guide. In my case, I was trying to initialize Firebase running a function, that's why it was not working for me

// firebase.config.ts

import {
  initializeApp,
  getApps,
  getApp,
  type FirebaseOptions,
  type FirebaseApp,
} from 'firebase/app';
import { getAuth, type Auth } from 'firebase/auth';

const firebaseConfig: FirebaseOptions = {
  apiKey: `${process.env.NEXT_PUBLIC_FIREBASE_API_KEY}`,
  authDomain: `${process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN}`,
  databaseURL: `${process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL}`,
  projectId: `${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}`,
  storageBucket: `${process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET}`,
  messagingSenderId: `${process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID}`,
  appId: `${process.env.NEXT_PUBLIC_FIREBASE_APP_ID_APPLICANT}`,
  measurementId: `${process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID_APPLICANT}`,
};
const app: FirebaseApp =
  getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
const auth: Auth = getAuth(app);

export { auth };
// signin.ts
import { type UserCredential, signInWithCustomToken } from 'firebase/auth';
import { auth } from '../config';

type SigninWithCustomToken = (customToken: string) => Promise<UserCredential>;
export const signinWithCustomToken: SigninWithCustomToken = async (
  customToken: string,
): Promise<UserCredential> => {
  const token = customToken.trim();
  if (token.length === 0) await Promise.reject(new Error('Token is empty'));
  return await signInWithCustomToken(auth, token);
};

I have multiple Firebase Apps and I need to change this 2 properties, based on each application

{
   ...
   appId: `${process.env.NEXT_PUBLIC_FIREBASE_APP_ID_APPLICANT}`,
   measurementId: `${process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID_APPLICANT}`,
}

I'm still thinking that it should be possible to only change those properties, but I don't know how to do it yet.
I hope this can be helpful for you.

@romainjacquel
Copy link

romainjacquel commented Sep 3, 2023

Hi, thank you for your help, this tutorial was very helpful for me 👌

However i have this error in my console, she don't want to desapear...

image

Do you have any idea ? All my module all installed with yarn, my project i also run with yarn.

Thanks for your help 👍

@google-oss-bot
Copy link
Contributor

Hey @rzych112. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

@google-oss-bot
Copy link
Contributor

Since there haven't been any recent updates here, I am going to close this issue.

@rzych112 if you're still experiencing this problem and want to continue the discussion just leave a comment here and we are happy to re-open this.

@firebase firebase locked and limited conversation to collaborators Oct 15, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants