Prevent pages access to un authorized user in next js

I am creating a login page and dashboard for the admin panel using NExtjS and react-redux. Below is the code I have tried. If I login using Id and password I can login and get all the values from the state and everything works fine. The problem is if I tried to access the dashboard URL directly it says Cannot read properties of null (reading 'name')
how can I redirect the user to the login page instead of getting up to return the statement ???

import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';

const Dashboard = () => {

  const { auth } = useSelector((state) => state);
  const router = useRouter();

console.log(auth) 
// I can get all the objects from state and cookies are set as state for browser reload so everything is fine here.

  useEffect(() => {
    if (!auth.userInfo && auth.userInfo.role == 'user') {
      router.push('/admin');
      console.log('I am here');
    }
  }, []);
  return <h1>{auth.userInfo.name}</h1>;
};


export default dynamic(() => Promise.resolve(Dashboard), { ssr: false }); ```
type or paste code here

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.