[Vuejs]-How to redirect to login if not authenticated in Vue with DRF

5👍

You can do this in your Vue Router beforeEach guard. This runs on every route before directing to the requested page, including on a new page load or refresh, so it’s ideal for handling this type of logged in check.

    router.beforeEach((to, from, next) => {
      const token = localStorage.getItem('user-token')
        // If logged in, or going to the Login page.
        if (token || to.name === 'Login') {
          // Continue to page.
          next()
        } else {
          // Not logged in, redirect to login.
          next({name: 'Login'})
        }
      }
    });

Note: this code assumes your login route name is Login, so you can update that accordingly.

I also recommend using VueX to get and store your auth token, and your default value for the token in your store can be from local storage or a cookie. That just makes it more efficient, checking the Vuex store value instead of getting it from local storage or the cookie every time.

Vue Router navigation guards: https://router.vuejs.org/guide/advanced/navigation-guards.html

Leave a comment