【问题标题】:Accessing Cookie client-side with Next JS使用 Next JS 访问 Cookie 客户端
【发布时间】:2023-02-22 03:03:50
【问题描述】:

使用cookies-next包, 根据他们的文档,访问 cookie 客户端就像getCookie('key'); - client side 一样简单

我的 Next JS 应用程序中有一个简单的功能,

  const handleAddToCart = () => {
    const token = getCookie('cookie-token')

    console.log('token', token)
}

我看到日志中没有返回任何内容。虽然我在检查我的开发人员工具时确实看到 cookie 确实存在。我在这里做错了什么?

【问题讨论】:

    标签: authentication cookies next.js server-side-rendering


    【解决方案1】:

    如果您知道 cookie 有价值,只需刷新页面,您就可以看到它们!但是您的 cookie 没有任何价值,所以首先检查“setCookie”!

    如果你想加载其他组件!你必须使用“useEffect”。

    const token = getCookie('cookie-token')
    const [myToken , setMyToken] = useState("")
    
    useEffect(() => {
      console.log(token)
      setMyToken(token)
    },[token])
    console.log(myToken)
    
    

    如果你有 SSR 组件:

    export const getServerSideProps = ({ req, res }) => {
      const token = getCookie('cookie-token', { req, res });
      ...
    }
    

    【讨论】:

      【解决方案2】:

      在将响应发送到 cookie 之前,您已经在 api 文件中设置了 cookie。您在用户登录时设置令牌,所以可能在 pages/api/auth.signin 端点

      import { setCookie } from "cookies-next";
      
      const token=setTokenHere // what ever library you are using
      // we tell client that, I want you to store this piece of information as a cookie
      setCookie("jwt", token, { req, res, maxAge: 60 * 6 * 24 });
      

      在客户端,每当您需要访问此 cookie 时

       import { getCookie } from "cookies-next";
       // "jwt" is key, 
       const jwtToken = getCookie("jwt");
      

      【讨论】:

        猜你喜欢
        • 2014-05-10
        • 2018-04-02
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多