在服务器上访问 Next.js 客户端状态

Access Next.js client state on the server

我正在尝试使用 getServerSideProps 函数在我的 Next.js 应用程序中获取动态数据。该请求必须包含一个令牌,该令牌存储在客户端,用于在后端对用户进行身份验证。

我试过以下方法:

export async function getServerSideProps(context) {
  const token = window.localStorage.getItem('token')
  const data = await axios.get("/data", { headers: { Authorization: `Bearer ${token}` }});
  return { props: { data } };
}

但我得到 ReferenceError : window is not defined,这是有道理的,因为请求是在服务器上发出的,而 window 对象不存在(它只存在于客户端)。

我可以在 getServerSideProps 中访问客户端状态或在服务器上存储下一个状态吗?如果没有,看起来唯一的方法就是在客户端发出请求。

改为使用 cookie。因为getServersideProps发生在服务端渲染,所以window或者localStorage无法访问。使用cookies和js-cookie库设置和获取token。