programing

Best practices to sync the client side vuex state to the server side state?

prostudy 2022. 7. 11. 21:04
반응형

Best practices to sync the client side vuex state to the server side state?

I have cloned vue-hackernews-2.0, a Vue.js app with SSR and vuex.

This app listens on port 8080, while my api server listens on 3000 in my local dev environment.I am trying to implement user authentication in it, using jwt.

when the client recieves the token from api server,the client state updates with the token, But How do I make the server side state aware that the user is logged in ?

In general, how to sync client side and server side state?

An ugly hack I thought of is that when the user logs in with correct credentials, the api server should open a socket connection with the 8080 server and trigger a state update on server side? Is it an acceptable/scalable solution? What are the best practices regarding this?

MORE DETAILS.. (a) in router I implemented the navigation guard :

      ....
      if (router.app.$store.getters.isLoggedIn)  next()
      else  next('/login')
      ...

로그인 페이지에서 액션을 api 서버(포트 8080의 vue 서버가 아님)에 투고하고 토큰을 클라이언트 측 상태로 저장합니다.그러나 로그인한 대시보드 페이지를 새로고침하면 서버 측 상태에서 토큰을 찾을 수 없습니다.isLoggedIn위는 false를 반환하고 로그인 페이지를 렌더링하려고 합니다.위의 코드를 참조해 주세요.클라이언트측의 DOM은 서버측의 DOM과 일치하지 않습니다.클라이언트는 클라이언트측의 DOM을 재렌더하려고 합니다.

Well, you wrote you're using jwt.

So the server doesn't need to know if the user is logged in.

As long as the client provides this jwt on every request (header, cookie, (body)), the server can authorize these requests.

To proper handle jwt, you could use the npm package:

const JWT = require('jsonwebtoken')

Issuing a token:

const token = JWT.sign({
    userId: user.id,
    moreData: undefined,
  },
   'somRandomLongPrivateKey123', // protect it, env var?
  {
    expiresIn: '2d',
  })

Middleware to validate the token:

module.exports = async (req, res, next) => {
try {
  const payload = JWT.verify(token, 'yourprivatekey') 
  req.user = User.find(payload.userId) 

  next()

} catch(e) {
  return res.status(401).send('no valid token')  
}

ReferenceURL : https://stackoverflow.com/questions/56714456/best-practices-to-sync-the-client-side-vuex-state-to-the-server-side-state

반응형