如何在NextJS 13中设置受保护的路由?

huangapple go评论53阅读模式
英文:

How to set protected routes with NextJS 13?

问题

I have been working on a website whose major component is a student and faculty login portal. Now, I have managed to generate a JWT and store it as a cookie in the browser and on successful student login, it takes you /student

然而,如果有人只是在 URL 中键入 /student,它仍然会重定向。您可以在下面查看完整的代码:
https://github.com/shivpreet16/event-junction

I am not sure how to set /student as a protected route so as to make it inaccessible by simply typing in the URL. I tried to Chat GPT my way through this and wrote /utils/withAuth:

我不确定如何将 /student 设置为受保护的路由,以使它无法通过简单地在 URL 中输入来访问。我尝试通过 Chat 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;

And during export default in /student.js, I wrote:
export default withAuth(student)

/student.js 中的导出默认时,我写了:
export default withAuth(student)

However, this does not seem to recognize the withAuth function itself:

但是,似乎无法识别 withAuth 函数本身:

如何在NextJS 13中设置受保护的路由?

Any idea how to work this out?
有什么想法如何解决这个问题?

英文:

I have been working on a website whose major component is a student and faculty login portal. Now, I have managed to generate a JWT and store it as a cookie in the browser and on successful student login, it takes you /student

However, if someone simply types /student into the URL, it still redirects. You can check out the full code down here:
https://github.com/shivpreet16/event-junction

I am not sure how to set /student as a protected route so as to make it inaccessible by simply typing in the URL. I tried to Chat GPT my way through this and wrote /utils/withAuth :

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

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

    useEffect(() =&gt; {
      if (!isAuthenticated()) {
        Router.push(&#39;/&#39;);
      }
    }, []);

    if (!token) {
      return null;
    }

    return &lt;WrappedComponent {...props} /&gt;;
  };

  return Auth;
};

export default withAuth;

And during export default in /student.js, I wrote:
export default withAuth(student)

However, this does not seem to recognize the withAuth function itself:

如何在NextJS 13中设置受保护的路由?

Any idea how to work this out?

答案1

得分: 2

I created a function that I call inside every server component that's supposed to be protected.

protectedPage.tsx:

import { cookies } from "next/dist/client/components/headers";
import { redirect } from "next/navigation";

export default function protectedPage() {
  const cookieStore = cookies();
  const accessToken = cookieStore.get("accessToken");
  const refreshToken = cookieStore.get("refreshToken");

  if (!accessToken || !refreshToken) {
    return redirect("/auth/sign-in");
  }
}

Example usage:

export default function Test() {
  protectedPage();
  return (
    <>
      <h1>hello this is protected</h1>
    </>
  );
}
英文:

I created a function that I call inside every server component that's supposed to be protected.

protectedPage.tsx:

import { cookies } from &quot;next/dist/client/components/headers&quot;;
import { redirect } from &quot;next/navigation&quot;;

export default function protectedPage() {
  const cookieStore = cookies();
  const accessToken = cookieStore.get(&quot;accessToken&quot;);
  const refreshToken = cookieStore.get(&quot;refreshToken&quot;);

  if (!accessToken || !refreshToken) {
    return redirect(&quot;/auth/sign-in&quot;);
  }
}

Example usage:

export default function Test() {
  protectedPage();
  return (
    &lt;&gt;
      &lt;h1&gt;hello this is protected&lt;/h1&gt;
    &lt;/&gt;
  );
}

答案2

得分: 0

So, I managed to figure it out. We basically used cookie-next to store the JWT in the front end. Then, before pushing the protected route, we used a useEffect() . The code snippet looks like:

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

This code runs exactly once before the /student route gets displayed. It checks for the existence of the cookie and uses the email details in the cookie to get to the right information on the student page.

英文:

So, I managed to figure it out. We basically used cookie-next to store the JWT in the front end. Then, before pushing the protected route, we used a useEffect() . The code snippet looks like:

useEffect(() =&gt; {
    if(!getCookie(&#39;student_cookie&#39;)){
        router.push(&#39;/&#39;)
    }
  }, [])

This code runs exactly once before the /student route gets displayed. It checks for the existence of the cookie and uses the email details in the cookie to get to the right information on the student page.

huangapple
  • 本文由 发表于 2023年3月31日 21:33:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定