【发布时间】:2020-06-19 15:57:08
【问题描述】:
我在 next.js 应用程序中使用 localStorage 令牌。我试图在 getInitialProps 页面上获取 localStorage,但它返回 undefined。
这是一个例子,
Dashboard.getInitialProps = async () => {
const token = localStorage.getItem('auth');
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { 'Authorization': token }
});
const data = await res.json();
return { page: data };
}
【问题讨论】:
-
getInitialProps完全在服务器端运行,而LocalStorage仅在客户端存在,因此您无法访问它。使用另一种发送数据的方式,如 cookie、http 正文等。 -
与始终在服务器端运行的新
getServerSideProps不同,getInitialProps实际上可以在客户端转换期间在客户端运行。但我同意 cookie 在这种情况下是更好的解决方案。
标签: authentication local-storage next.js