【问题标题】:In Next.js 13 with turbopack, how do I access cookies without getServerSideProps?在带有 turbopack 的 Next.js 13 中,如何在没有 getServerSideProps 的情况下访问 cookie?
【发布时间】:2023-01-13 06:18:32
【问题描述】:

我有一个在 cookie 中保留一些值的应用程序。我知道还有其他工具,例如 useStateuseContext 等...但是这个特定的应用程序与将信息存储在 jwt 中的库一起使用,因此我必须通过获取 jwt 来读取某些值。我正在将应用程序从 next.js 12(使用 webpack)移植到 next.js 13(使用 turbopack)。

我已经在结构上移植了应用程序以适应 next.js 13 的 app 样式路由。我的页面都放在各自的文件夹中,子布局在 app 目录中,我有一个主布局和主页直接在app 目录。

next.js 12 中受保护页面的旧代码如下所示:

受保护的.tsx

import type { NextPage } from 'next';
import { GetServerSideProps } from 'next';
import { useContext } from 'react';

//@ts-ignore
import Cookies from 'cookies';

const Protected: NextPage = (props: any) => {
  if (!props.authorized) {
    return (
      <h2>Unauthorized</h2>
    )
  } else {
  return (
    <div className="max-w-md">
      <h1 className="font-bold">This is the Protected Section</h1>
    </div>
  )}
}

export const getServerSideProps: GetServerSideProps = async ({ req, res, query }) => {
  const { id } = query
  const cookies = new Cookies(req, res)
  const jwt = cookies.get('<MY TOKEN NAME>')
  if (!jwt) {
    return {
      props: {
        authorized: false
      },
    }
  }

  const { verified } = <MY TOKEN SDK INSTANCE>.verifyJwt({ jwt })

  return {
    props: {
      authorized: verified ? true : false
    },
  }
}

export default Protected

我现在将此页面移到了它自己的目录中。

Next.js 13 https://beta.nextjs.org/docs/data-fetching/fundamentals 不支持“getServerSideProps”。文档说“新的应用程序目录不支持以前的 Next.js API,例如 getServerSideProps、getStaticProps 和 getInitialProps”。那么我如何更改我的代码以在 Next.js 13 中工作?

附言我知道它的样子,但这个 cookie 不处理用户身份验证。我知道有人可以更改 cookie 并获得对受保护页面的访问权限。这只是具有我已部署的其他安全机制的大型应用程序的一小部分。

【问题讨论】:

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


    【解决方案1】:
    import { cookies } from "next/headers";
    

    这是next/headers.jscookie 函数

    function cookies() {
        (0, _staticGenerationBailout).staticGenerationBailout('cookies');
        const requestStore = _requestAsyncStorage.requestAsyncStorage && 'getStore' in _requestAsyncStorage.requestAsyncStorage ? _requestAsyncStorage.requestAsyncStorage.getStore() : _requestAsyncStorage.requestAsyncStorage;
        return requestStore.cookies;
    }
    

    这是向客户端发出获取 cookie 的请求。在app 目录中,你在服务器上,你可以在组件中编写它。

    const cookie = cookies().get("cookieName")?.value
    

    【讨论】:

    • 根据我得到的错误,next 似乎没有 cookies() 功能......?我不知道为什么,但这是我的页面gist.github.com/ChristianOConnor/… 的源代码。我收到这个错误Error: Cannot read properties of undefined (reading 'has')imgur.com/a/WgnC24Z
    • has 用于集合。看起来不是一套。你能不能请console.log(cookies().get("cookieName")?.value)
    • 我得到了同样的错误,但我刚刚意识到也许我的 cookie 没有设置?我尝试在另一个文件中设置 cookie,例如 cookies().set('lit-auth', litjwt, { expires: 1 });。但我刚刚意识到,根据文档“cookies 功能允许您从服务器组件读取 HTTP 传入请求 cookies。它是只读的,这意味着您无法设置/删除传出请求 cookies。”...那么如何在 Next.js 13 中设置 cookie?
    • 你可以检查 chrome 开发工具 cookie
    • 我修复了它,我用 cookies-next 设置了 cookie,我能够完全按照你的建议获取 cookie。它适用于 webpack,但不适用于 turbopack。使用 turbopack 我得到 TypeError: Class extends value #&lt;Object&gt; is not a constructor or null 这没有意义......无论如何感谢您的帮助。我现在接受你的回答。
    【解决方案2】:

    您可以通过"cookies-next" library 访问您的 cookie。

    pnpm i cookies-next

    检查一下:https://www.npmjs.com/package/cookies-next

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多