所以我在 Next.js 应用程序中创建身份验证逻辑。我创建了/api/auth/login
处理请求的页面,如果用户的数据良好,我将httpOnly
使用 JWT 令牌创建一个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 …
Run Code Online (Sandbox Code Playgroud) cookies node.js server-side-rendering higher-order-components next.js
我想包装我的整个应用程序,以便除非用户登录,否则无法访问它。如果用户未登录,我设法将用户重定向到登录页面,但是,我仍然看到之前的私有路由闪现发生重定向。如何避免这种情况?