Search code examples
javascriptvue.jsvuejs2vuexvue-router

Vue Router access route only from certain page


After a user has logged in the first time I redirect him to the page CreateProfile where he types in all the profile information. Afterwards I want to make this site not accessible anymore, such as if the user types the URL into the browser (e.g. www.myproject.com/createProfile).

How can I make sure that only the redirection from my login page has access to the CreateProfile page? That is, if the user types in the URL manually he will be redirected e.g. to the 404 page.

Currently my route for CreateProfile looks the following:

{
  path: '/createprofile',
  name: 'CreateProfile',
  component: CreateProfile,
  beforeEnter: (to, from, next) => {
    if (store.getters.getUserStatus == true) {
      next()
    } else {
      next({ name: 'Login' })
    }
  }
}

Thanks!!


Solution

  • You can check the from route object in the beforeEnter navigation guard to test the previous route location.

    For example, check that the from.name property is Login, which will only be true when there has been the redirect you want. (Assuming you don't also provide a <router-link> from Login):

    beforeEnter: (to, from, next) => {
      const isRedirected = from.name === 'Login';
      if (isRedirected && store.getters.getUserStatus == true) {
        next()
      } else {
        next({ name: 'Login' })
      }
    }