yangfan0095 / react-koa2-ssr

a Isomorphic framework demo for react server side rendering ( react 同构工程项目骨架,基于create-react-app 和 koa2生成器搭建。)
301 stars 55 forks source link

Is is possible to use localStorage before rendering in browser? #7

Open nickzym opened 6 years ago

nickzym commented 6 years ago

I use token to authenticate users. It just like the following code

if(localStorage.jwtToken) {
      setAuthorizationToken(localStorage.jwtToken);
      try {
          store.dispatch(setCurrentUser(jwtDecode(localStorage.jwtToken)));
      } catch (err) {
          store.dispatch(setCurrentUser({}));
      }
  }

But localStorage is not available in node environment where inside renderToString function.

Any possible solution for this?

yangfan0095 commented 6 years ago

you can add your token on url query .and then node can get token .

nickzym commented 6 years ago

我上面写的代码的意思是,在我渲染首页的时候,可以通过localStorage获取登录过的token。但是服务端渲染的话,无法在node renderToString的时候,得到locaStorage存的东西啊。

yangfan0095 commented 6 years ago

你可以把token 放到cookie 里面,ssr服务的根域名和 你认证权限的根域名要保持一直。 通过设置cookie 的domain属性 去控制根域名下子域名之间的cookie共享 具体参见https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie 。 有服务端数据共享的需求用locaStorage 就不能满足了。😕

nickzym commented 6 years ago

感谢您的建议,我现在就是用cookie没用localstorage。

yangfan0095 commented 6 years ago

🙂