How to set beforeResolve navigation guard in Nuxt.js

Viewed 8671

Is there a way to add beforeResolve navigation guard in nuxt.config.js?

My nuxt.config.js

module.exports {
    ...
    router: {
        beforeResolve(to, from, next) {
            if (this.$store.getters.isLoggedIn)
                 next('/resource')
        }
    }
    ...
}

But its never gets called!

I've been trying to achieve a redirection before the component is mounted based on the users logged in state on the vuex store.

1 Answers

You have 2 options for this. You can set a global rule via the middleware or in the respective page.

// middleware/route-guard.js
export default function ({ app }) {

    app.router.beforeResolve((to, from, next) => {
        if (app.store.getters.isLoggedIn) {
            next('/resource')
        } else {
            next();
        }
    });

}

// Nuxt Page Component
export default {
    beforeResolve (to, from, next) {
        if (this.$store.getters.isLoggedIn) {
            next('/resource')
        } else {
            next();
        }
    }
  }
Related