【发布时间】:2025-11-30 04:00:01
【问题描述】:
所以我在我的 Next.js 应用程序中创建身份验证逻辑。我创建了处理请求的/api/auth/login 页面,如果用户的数据良好,我将创建一个带有JWT 令牌的httpOnly cookie 并将一些数据返回到前端。这部分工作正常,但我需要一些方法来保护某些页面,以便只有登录的用户才能访问它们,我在为此创建 HOC 时遇到问题。
我看到的最好的方法是使用 getInitialProps 但在 Next.js 网站上它说我不应该再使用它了,所以我考虑使用 getServerSideProps 但这也不起作用,或者我可能做错了什么。
这是我的 HOC 代码:
(cookie 存储在userToken 名称下)
import React from 'react';
const jwt = require('jsonwebtoken');
const RequireAuthentication = (WrappedComponent) => {
return WrappedComponent;
};
export async function getServerSideProps({req,res}) {
const token = req.cookies.userToken || null;
// no token so i take user to login page
if (!token) {
res.statusCode = 302;
res.setHeader('Location', '/admin/login')
return {props: {}}
} else {
// we have token so i return nothing without changing location
return;
}
}
export default RequireAuthentication;
如果您对如何使用 cookie 在 Next.js 中处理身份验证有任何其他想法,我将不胜感激,因为我是服务器端渲染 react/auth 的新手。
【问题讨论】:
标签: node.js cookies next.js server-side-rendering higher-order-components