DEV Community

How to use Global Navigation Guards with Nuxt Middleware, and why you absolutely should NOT

Robert Hustead on August 09, 2019

TLDR: It's possible to use Global Navigation Guards with Nuxt by using Middleware In the Middleware, you have access to the context, by which you...
Collapse
 
julpat profile image
julpat

Well :)
Its quite simple.. imagine that middleware is (!) router.beforeEach


export default function ({ store }) {
  if(store.state.isUserEditing) {
      if(confirm("Are you sure?")) {
        store.commit('userEditing', false);
        next();
      } else {
        next(false);
      }
  }
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
minicatscb profile image
minicatsCB

Where does next() come from?
For me, even a simple code like this:

export default function() {
  next(false)
}
Enter fullscreen mode Exit fullscreen mode

throws an error saying: "Reference error: next is not defined".

Collapse
 
julpat profile image
julpat

Sorry, that was taken just as an example from the article, but agree, can be confusing.

In docs you can find this example of middleware/auth.js

export default function ({redirect, store}) {
    const isAuthenticated = store.state.auth.user ? true : false
    if (!isAuthenticated) {
      redirect({name: 'auth'})
    }
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
swsalim profile image
Yuyu

Hi, I stumbled upon this issue on Stack Overflow that fits in what I'm trying to achieve: stackoverflow.com/questions/491866...

The first thing that came to my mind is to use the navigation guards to check and load the right component.

Does navigation guards work on page load/refresh?

Collapse
 
husteadrobert profile image
Robert Hustead

Hi! I believe it depends on the navigation guard.

Component navigation guards like beforeRouteLeave or beforeRouteUpdate will not run on page load/refresh. However, something like beforeRouteEnter will run on page load/refresh.

The navigation guard beforeEnter should also run on page load/refresh.

Hope that helps!

Collapse
 
kp profile image
KP

@husteadrobert thanks for the article. Would love to see how you implement non-global (page-based) navigation guards in Nuxt (not Vue).

Collapse
 
dubemkizito profile image
Izuorah Dubem kizito

Nice article, I think for someone that needs to do an auth ceck using middleware should be fine, since I need to check for the auth status of every page.