【问题标题】:How can we access secure httpsonly cookie in next js applicationHow can we access secure httpsonly cookie in next js application
【发布时间】:2022-12-27 19:42:10
【问题描述】:

we are calling https://demo.com/auth/session in next js application

backend team set the response cookie as secure HttpOnly cookie

const session = await (
  await fetch(
   `https://demo.com/auth/session`,
    requestOptions
      )).json();

console.log("cookies",ctx?.req?.headers?.cookie);

backend cookies code

Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly

how can we access secure HttpOnly cookie in next js application

【问题讨论】:

  • Where in your Next.js app are you calling that endpoint, client-side or server-side?
  • calling end point at server-side..

标签: javascript reactjs cookies next.js httpcookie


【解决方案1】:

You cant access HttpOnly cookie by using client side JavaScript. It is intended to be like that because of security(to prevent some type of attacks).

Please use it as a reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

【讨论】:

  • That's true, but I am accessing this HTTPOnly cookie in the server side. Can i access this cookie in the server side (NextJS)
【解决方案2】:

I am not sure but perhaps yes.

inside your getServerSideProps you can do:

let mycookie = getCookie("cookieName", {ctx.req, ctx.res});

getCookie is a method from package "cookies-next" and ctx is the context object passed in the getServerSideProps automatically by nextjs. getCookie() will access the req headers and get the cookie by its name. Again I am not sure whether this will work or not. :)

Edit: Well, accessing httpOnly cookie, is a very bad Idea actually :)

【讨论】:

    猜你喜欢
    • 2022-12-28
    • 2022-12-27
    • 2022-12-02
    • 2022-12-19
    • 2022-12-19
    • 2022-12-04
    • 2022-12-01
    • 2022-11-20
    • 2022-12-02
    相关资源
    最近更新 更多