NUXT middleware store state is empty even though Vuex in dev tools showing data

Viewed 1620

I am using NUXT 2.0 (mode = universal) with the Auth module which for me is setup & working correctly!

When viewing any page after logging if I use example code. I can see the user no problem.

<div v-if="$auth.loggedIn">
  Logged In {{ $auth.user.email}}
</div>

If I look at VUEX in Dev tools I can also see the state.auth.user: https://d.pr/i/3pXcLa

But if I add some middleware and load the page the store.state.user is empty. Example simple code.

export default function ({ store, redirect }) {
  console.log(store.state.auth)
}

Am I using the middleware correctly?

Really hope someone can help.

1 Answers

Whenever you reload the page your store gets reloaded to its initial state because its on the client side.

That means whenever you refresh your page all your data in your Vuex Store gets lost to its initial state.

1 Solution could be:

-> You create an cookie with your Logged user and check everytime in the middleware if that cookie contains that logged in user.

In universal mode the middleware only works on the serversite so you cant access the window that means you cant access cookies. But there is another way how to access it:

You destructure the property req:

export default function ({ store, redirect, req }) {
  console.log(req.headers.cookies)
  // or req.headers.cookie ? i am not sure here
}

Now you have access to the cookie.

I would recommend to use JWT for this. Whenever you log in successfully you should generate an JWT on the server and store it in your cookie.

Everytime you try to access some "secret" pages you send the JWT that is stored in the cookie to the server back to validate if the JWT is still valid or not and if it is then you let the user move on else you decline it.

Related