Router START_LOCATION is not only true for start location

I am using the test if (from === START_LOCATION) inside router.beforeEach to check if this is the initial start, so that I can do an auto signing if there is a token available.
And that works fine…
But the problem is that if the user goes to the login page, I have a next("/") call after doing the auto signing, so the user won’t be presented with the login page when he is already logged in.
This makes the beforeEach being called again ( as I guess it should), but then the test if (from === START_LOCATION) is still true, which makes the auto signin being called again.
I can write a workaround for this but was just curious if this is a bug or a feature or am I not seeing something here?

I don’t know if it’s a bug, but I think the crux of your issue is in the implementation; you shouldn’t rely on the path to determine if the user should be signed in. I’d refactor this to make it less brittle.

Without knowing anything about your app, the general approach is to check for a token and if the user is already authenticated. If the token exists, but the user isn’t auth’d, then go ahead and auth them.

I handled it by doing something like this

if( from === Router.START_LOCATION && ! store.getters[‘appActive’]){
// init app
} else {
// do normal check

Yes, that’s what I do. I do not rely on that test to determine if the user should be signed in, I am using JWT… :slight_smile:
But the prb is when I use next() to redirect to a different page than login, then the beforeEach is called again and that test is still true…

Yes, this is what I do… As I said, the problem is in the next() call and that beforeEach is called one more time and that test is still true…

What would be a good way to initialize an app from within Vue instance. I see a lot examples on the web setting up auth etc in main.js before creating Vue instance itself. Vue router seems to run before anything else thus START_LOCATION seems like a logical way to check if app is running for the first time.


Doing it within a Vue instance, the beforeEach router hook is correct, I just wouldn’t bother checking against the START_LOCATION. It doesn’t matter if it’s the first load, what matters is the auth state. So rather than having an if statement against the route location, use an if statement against the auth status.

Auth flow is app specific, but generally you should just need this pseudo logic:

  • No token exists, redirect to login (add a route meta check if some routes should still be accessible)
  • Token exists, proceed and use it with your Axios interceptors (I’d setup a check in the interceptor to use the stored token if it exists)
  • And of course, in your response interceptor you’ll want some logic to handle the refresh_token if the returned status is a 401.

Hmmm… Ok, that sounds like a better plan. Thx… :slight_smile: