简体   繁体   中英

Nuxt middleware not triggered upon initial render

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.

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) => {
  ...

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