1

The following code is meant to check the role of the user. The middleware runs everytime the site is reloaded are a new route is taken.

// Some nuxt middleware
import * as firebase from 'firebase/app'
import 'firebase/auth'

export default function ({ app, store, route, redirect }) {
  app.router.beforeEach((to, from, next) => {
    // For some reason, this does not load every time.
    firebase.auth().onAuthStateChanged((userAuth) => {
      if (userAuth) {
        console.log(userAuth)
        firebase
          .auth()
          .currentUser.getIdTokenResult()
          .then(function ({ claims }) {
          // some auth stuff
    })
  })
}

For some reason, if the site is reloaded this user auth function always returns null. This leads to that the rest of the functions fail due to the unknown user data / user roles.

firebase.auth().onAuthStateChanged((userAuth) => {...})

So my question is, why does the upper function return null when the site is reloaded?

ps. Everything works normal if a new route is taken, it only fails when site is reloaded.

kissu
  • 40,416
  • 14
  • 65
  • 133
Marcel Klein
  • 117
  • 1
  • 1
  • 9

1 Answers1

0

beforeEach is a guard triggered when you navigate from a page to another page thanks to vue router, aka using <nuxt-link> or $router.push.

On the initial page load, there is no navigation because you're rendering the content generated by the server, not the client directly.

Definition of a middleware from Nuxt's documentation

Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layout).

Notice, before rendering. This means that a middleware will be run as your beforeEach and on initial render.
Hence, you can totally strip the router guard part and simply let the middleware as this

export default function ({ app, store, route, redirect }) {
  firebase.auth().onAuthStateChanged((userAuth) => {
  ...
kissu
  • 40,416
  • 14
  • 65
  • 133
  • I finally had the time to test and think about it. I already tried it some time ago but it is not my main problem. The big problem for me is that the: firebase.auth().onAuthStateChanged((userAuth)=>{}) always returns "null" on page reload. Doesnt matter if it is inside the beforeEach guard or outside. – Marcel Klein Jun 30 '21 at 15:37
  • I just found that post: https://stackoverflow.com/questions/50683852/sometimes-firebase-auth-onauthstatechanged-returns-user-of-null-when-i-refresh I will try to find a Workaround based on this :) – Marcel Klein Jun 30 '21 at 15:39
  • Nuxt middleware-wise, it should work. Looks like `firebase` is using some listener for it to be triggered indeed. @MarcelKlein – kissu Jun 30 '21 at 15:41