Impossible to use middlewares with Firebase and NuxtJS 3

Viewed 54

I'm trying to use Firebase authentication on an example project. Authentication is working as expected, but as soon as I want to use middlewares to prevent users from accessing admin pages or to access login page whereas already logged in, it's impossible.

I have been trying for hours, but nothing worked.

Here is my package.json:

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "nuxt": "3.0.0-rc.6"
  },
  "dependencies": {
    "firebase": "^9.9.2"
  }
}

My App.vue

<template>
  <div>
    <NuxtPage />
  </div>
</template>

My folders:

app.vue
nuxt.config.ts
package.json
...
pages/
-- index.vue
-- login.vue
-- register.vue
composables/
-- useFirebase.ts
-- useFirebaseUser.ts
plugins/
-- firebase.client.ts

useFirebase.ts only contains Firebase functions.

useFirebaseUser here:

import type {User} from "firebase/auth";

export const useFirebaseUser = (init?:User|null) => useState<User|null>("user", () => init ?? null);

Now my firebase.client.ts plugin:

import { initializeApp } from "firebase/app";
import { onAuthStateChanged, getAuth } from "firebase/auth";

export default defineNuxtPlugin(async (nuxtApp) => {
    const firebaseConfig = {
        // ...
    };

    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const firebaseUser = useFirebaseUser(auth.currentUser);
    onAuthStateChanged(auth, (user) => {
        console.log("auth state changed =", user);
        firebaseUser.value = user;
    });
});

I have tried to use addRouteMiddleware within the plugin but then the page that uses it says it doesn't exist...

I have tried to declare a middleware in middleware directory and to use getAuth() from Firebase, but it says no Firebase app was initialized. I think the plugins are being loaded after the middlewares.

I have tried to provide a variable via:

return {
 provide: { auth: () => getAuth(app) }
}

At the end of the plugin, but it says "$auth" is not a function when I access it in the middleware via useNuxtApp.

I also tried:

nuxtApp.provide("auth", getAuth(app))

Which simply doesn't work as getAuth().currentUser gets its value once onAuthStateChanged was executed, after the page was loaded, making it useless because it will always give null or undefined.

Does someone know a magic way to use middlewares with Firebase authentication?

0 Answers
Related