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.

1
  • Hey, sadly I could not implement a proper solution yet I am still looking for something. Commented Jul 6, 2021 at 17:14

1 Answer 1

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) => {
  ...
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I just found that post: stackoverflow.com/questions/50683852/… I will try to find a Workaround based on this :)
Nuxt middleware-wise, it should work. Looks like firebase is using some listener for it to be triggered indeed. @MarcelKlein

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.