webnext.jsnext-auth

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

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 '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)

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

Server Error

Any idea how to work this out?


Solution

  • 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.