简体   繁体   中英

Problem with getAuth() in a different route - SvelteKit

I am trying to set up Firebase email/password authentication in SvelteKit. In __layout.svelte I initialize my Firebase app:

<script lang="ts">
    import { onMount } from 'svelte';
    import { initializeApp } from 'firebase/app';

    onMount(() => {
        // Your web app's Firebase configuration
        const firebaseConfig = {
            apiKey: '***',
            authDomain: '***.firebaseapp.com',
            projectId: '***',
            storageBucket: '***.appspot.com',
            messagingSenderId: '***',
            appId: '***'
        };

        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
    });
</script>

For my login/signup route, I need to call getAuth() but whenever I do, I get an error:

<script lang="ts">
    import { onMount } from 'svelte';
    import { getAuth, connectAuthEmulator } from 'firebase/auth';

    onMount(() => {
        const auth = getAuth(); //**ERROR HERE**
        connectAuthEmulator(auth, 'http://localhost:9099');
    });
</script>

The error I get is:

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

I think this is because I need to pass the app from __layout.svelte inside the getAuth() function, but I don't know how to export app to my login route to do so.

I suspect you are getting stuck in asynchronous issues...

file: Auth.svelte

<script lang="ts">
    import { onMount } from 'svelte';
    import { initializeApp } from 'firebase/app';
    import { getAuth, connectAuthEmulator } from 'firebase/auth';

    onMount(async () => {
        const firebaseConfig = {
            apiKey: '***',
            authDomain: '***.firebaseapp.com',
            projectId: '***',
            storageBucket: '***.appspot.com',
            messagingSenderId: '***',
            appId: '***'
        };

        // Initialize Firebase
        const app = await initializeApp(firebaseConfig);
    
        const auth = getAuth(); // This should work... 
        connectAuthEmulator(auth, 'http://localhost:9099');
    });
</script>

And in __layout.svelte:

<script>
    import Auth from "$lib/Auth.svelte";
</script>

<Auth />

Will this do it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM