如何使用NextJS 13设置受保护的路由?

7qhs6swi  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(167)

我一直在一个网站上工作,其主要组成部分是学生和教师登录门户网站。现在,我已经设法生成一个JWT,并将其作为cookie存储在浏览器中,并在成功的学生登录,它需要你/student
然而,如果有人只是简单地在URL中输入/student,它仍然会重定向。你可以在这里查看完整的代码:https://github.com/shivpreet16/event-junction
我不知道如何将/student设置为受保护的路由,以便通过简单地键入URL来使其无法访问。我试图通过聊天GPT来完成此操作,并编写了/utils/withAuth

import { useEffect } from 'react';
import Router from 'next/router';
import { getTokenCookie, isAuthenticated } from './auth';

const withAuth = (WrappedComponent) => {
  const Auth = (props) => {
    const token = getTokenCookie();

    useEffect(() => {
      if (!isAuthenticated()) {
        Router.push('/');
      }
    }, []);

    if (!token) {
      return null;
    }

    return <WrappedComponent {...props} />;
  };

  return Auth;
};

export default withAuth;

/student.js中的导出默认值时,我写道:export default withAuth(student)
然而,这似乎并不能识别withAuth函数本身:

你知道怎么解决吗?

hlswsv35

hlswsv351#

所以,我设法弄清楚了。我们基本上使用cookie-next在前端存储JWT。然后,在推送受保护的路由之前,我们使用useEffect()。代码片段如下所示:

useEffect(() => {
    if(!getCookie('student_cookie')){
        router.push('/')
    }
  }, [])

此代码在/student路由显示之前只运行一次。它会检查cookie是否存在,并使用cookie中的电子邮件详细信息来获取学生页面上的正确信息。
希望这有帮助!

相关问题