【问题标题】:How to handle server side Authentication in nextjs?如何在 nextjs 中处理服务器端身份验证?
【发布时间】:2021-11-24 19:39:00
【问题描述】:

我在 localstorage 中设置令牌并使用 (axios) 将其发送到每个请求,但问题是当我使用 getServerSideProps 时令牌未发送,因为无法在服务器端访问 localStorage .

我认为我应该使用 Cookie,我尝试了 js-cookies,但它在服务器上也不起作用。

是否有任何解决方案可以在服务器端以 getServerSidePropsgetStaticProps 的形式发送令牌?

【问题讨论】:

  • 您使用哪个库进行身份验证?
  • 实际上,我不使用任何我只是将令牌存储在 redux-store 和 localstorage 中,并与每个客户端请求一起发送。
  • 您无法从getServerSideProps 访问localStorage,因为它在服务器上运行。尝试使用 cookie 来存储令牌,或者将身份验证移至客户端。

标签: axios next.js server-side-rendering


【解决方案1】:

本地存储仅在客户端;使用getInitialProps

function Page({ stars }) {
    return <div>Next stars: {stars}</div>
}
        
Page.getInitialProps = async ({ req }) => {
    let token;
    
    // server
    if (req) return { page: {} };
    else {
        // client
        const token = localStorage.getItem("auth");
        const res = await fetch('https://api.github.com/repos/vercel/next.js', { headers: { Authorization: token }});
        const data = await res.json();
        return { page: data };
    }
};

export default Page

只要修改我的代码,正常就可以了

【讨论】:

  • 这并不能完全解决问题。首次加载页面并且getInitialProps 在服务器上运行时,身份验证逻辑不会运行。
  • 我目前正在发出需要在客户端进行身份验证的请求,但我认为这不是最好的方法,而且我没有很好地使用带有 nextjs 的 ssr。
猜你喜欢
  • 1970-01-01
  • 2021-09-04
  • 2016-05-01
  • 2015-03-31
  • 2023-03-05
  • 2013-10-26
  • 2011-11-04
  • 1970-01-01
  • 2018-02-26
相关资源
最近更新 更多