So.. in my application, at the Authentication
chapter, i have some questions.
First of all i have multiple components/routes, two of them being register
and login
.
Register
works fine, using my api, in respond i get an username
and account_id
, both being stored in database.
When trying to log in
, in respond i get username
and token
.. Now, when i access other routes in my website that can only be accesed if you're logged in, i need to detect if a token is present. How can i make like a global variable that has token
value and it can be accesed easily by other components ?
Store your token in cookie / localstorage and if you are using vuex you can store it in the state also.
If you are using Axios or any other tool for ajax requests, you can pass your token in headers and just pick it up from either cookie / localstorage.
state: {
token: Cookie.getJSON('token') || null,
},
mutations: {
setToken: (state, data) => {
state.token = data
Cookie.set('token', data)
}
},
actions: {
setToken (context, data) {
context.commit('setToken', data.token)
}
}
Check this - https://www.npmjs.com/package/js-cookie