Answer the question
In order to leave comments, you need to log in
How to do cookie validation in Nuxt middleware?
Hello, I'm using the vue-cookie library to manipulate cookies.
I want to implement a redirect to the authorization page if the user is not logged in.
I have 2 main questions:
1) Why is it necessary to store the token in the store if it is initially empty when entering the page? And the conditional state.token will not be set. You can take it directly from cookies (or not?).
2) Based on the first question, I started trying to check for cookies directly in the middleware, but I ran into the problem that this is not available in SSR and I can’t access cookies.
export default function({ redirect }) {
if (!this.$cookie.get("token")) {
return redirect("/welcome");
}
}
Answer the question
In order to leave comments, you need to log in
Kmk, storing data in the store is conditionally safer, because. cookies can be corrected from the console, and in the store changes can only be made through mutations.
And also the store is available in the middleware and wherever you want
export default function ({ store, redirect }) {
if (!store.getters['user/isAuthorized']) {
return redirect('/')
}
}
async nuxtServerInit({ commit, dispatch }, context){
const token = getCookie('token', context?.req?.headers?.cookie); //кастомная функция для удобного получения куков, вы их можете получать как хотите
if (token !== undefined && token !== null && token !== 'undefined' && token !== 'null'){
commit('user/SetUserToken', getCookie('token', context?.req?.headers?.cookie));
}
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question