R
R
Rufix2020-11-25 12:57:50
Vue.js
Rufix, 2020-11-25 12:57:50

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

2 answer(s)
A
Alexey, 2020-11-25
@AlexeyCaTHaR

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('/')
  }
}

And on the topic of the emptiness of the token = it all depends on what kind of routing and how the token is installed)

V
VegasChickiChicki, 2020-11-25
@VegasChickiChicki

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));
    }
  },

An example of getting a token on the server from cookies and writing it to storage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question