[英]Auth Nextjs website from getInitialProps with localstorage or cookie and Apollo
I have some problems with the auth process on Nextjs project.我在 Nextjs 项目的身份验证过程中遇到了一些问题。 From the example , it stores the token in cookies, but in
checkLoggedIn.js
it queries DB instead of get the token from cookie.在示例中,它将令牌存储在 cookie 中,但在
checkLoggedIn.js
它查询 DB 而不是从 cookie 中获取令牌。
I would like to get the token from cookie or localstorage in getInitialProps
, but in getInitialProps
, it can NOT see localstorage because it's still in server side.我想从
getInitialProps
cookie 或 localstorage 获取令牌,但在getInitialProps
,它看不到 localstorage 因为它仍在服务器端。 Is there any better way that I could auth user before component render?有没有更好的方法可以在组件渲染之前对用户进行身份验证?
Not sure is it possible to get the token from getToken
in apollo client.不确定是否可以从 apollo 客户端中的
getToken
获取令牌。
My current code is我目前的代码是
class DashBoard extends React.Component {
constructor(props) {
super(props)
}
componentDidMount () {
const decodeToken = verifyToken(localStorage.getItem('KEY'));
if (!decodeToken.mail) {
Router.push('/login');
} else {
this.props.loginSuccess(decodeToken.name, decodeToken.mail);
}
}
render () {
return (<div></div>)
}
}
Thank you谢谢
Here is what I did to solve it after few days of research (honestly, not the best documentation around)经过几天的研究,这是我为解决它所做的(老实说,不是最好的文档)
In the getInitialProps
, I took the headers from the requests and copied them over in my fetch
request.在
getInitialProps
,我从请求中fetch
标头并将它们复制到我的fetch
请求中。
Profile.getInitialProps = async ({ req }) => {
const headers = { ...req.headers }
const url = `http://localhost:3000/api/profile`
const data = await fetch(url, { headers }).then(res => res.json())
return { data }
}
Keep in mind that this only works on the server.请记住,这仅适用于服务器。 For the client, you can just pass
{credentials: 'include'}
to fetch
对于客户端,您只需传递
{credentials: 'include'}
即可fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.