I am managing performing a login and the login state using Vuex
. It is a standard procedure of:
- User submits their login details on a form
- The form dispatches a
Vuex
action to make anaxios
API call to a Node/Express endpoint/api/login
with the credentials - The response from the API if successful will send back the user's data which is stored in the
state.user
object through asetUser
mutation. A flag ofstate.user.isLoggedIn
is also set totrue
. - A JWT access token is sent to the user's browser and stored in a secure cookie to use over and over again until it expires. If it expires, a refresh token is used to generate a new JWT access token.
- The site's header displays the user's login information .e.g name
The above all works as expected. However if the user refreshes their browser, then Vuex
state gets emptied and the site header no longer shows the user information. To overcome this I stored state.user
into localStorage
in the browser as persisted data and repopulate the Vuex
store using the data in localStorage
on page refresh. If the user logs out, the localStorage
is cleared.
There are many routes that require checking if the user is logged in. I cannot rely on localStorage
because it can be manipulated by the user. If the user deletes their cookies which contains a JWT, then localStorage
is not being emptied and the site header still displays their log-in information. Therefore I need to do an API call on almost every page to check if the user is logged in and if not then to delete the localStorage
as well.
My question is:
- Where do I perform a log-in check every time a page/view is accessed? Is it whenever the Vue
app
is mounted or withinvue-router
using thebeforeEach
navigation guard? - If I use
beforeEach
invue-router
, is it going to crash the site by making an API call to/api/login
every time a user changes route? Is it normal practice to do this on every route? - Are there any other alternative patterns to keeping track of if the user is logged in or not?