【发布时间】:2023-01-13 06:18:32
【问题描述】:
我有一个在 cookie 中保留一些值的应用程序。我知道还有其他工具,例如 useState、useContext 等...但是这个特定的应用程序与将信息存储在 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