Restrict access to routes if you are not logged in to Vuejs

Asked

Viewed 648 times

5

I’m developing a Dashboard and I doubted how to forbid access to rotas if they are not logados, with this, I thought of some solutions that would use localStorage, but none is a sure solution.

What would be the right way to do that? I saw that many people have this doubt, and I couldn’t find a solution to it.

  • You are using the Vue-router?

  • @bfavaretto Yes, I’m using Vue-Router

  • I won’t be able to write an answer right now, but look at the Vue-router documentation. It allows you to intercept the route before you navigate to it. At this point you have to consult the server about access permissions, and only clear the route if the response is positive. This will generate a "loading" between routes.

1 answer

0


For those who even with the documentation had the same difficulty than I to implement, follows the code and a brief explanation.

In my main.js i defined globally

router.beforeEach((to, from, next) => {
    console.log(to)
    if(to.name == 'Dashboard'){
        alert('dashboard')
    }else{
        next()
    }

})

With this, it is already possible to restrict access without permission (I did not do any validation in this example), however, when trying to access via URL still possible, however, I managed to solve with the following code on my page Dashboard

<script>
    export default{
        beforeRouteEnter(to, from, next){
            if(to.meta.adminOnly === true){
                next('/')
            }
        }
    }
</script>

With this, just check if the user is logged in, if not, he would send it again to the login page /.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.