简体   繁体   中英

How to restrict user to display login page if already logged in using Reactjs

I am working on Reactjs and using nextjs framework, I am working on "Login Logout" module and i just want that if user already logged in ( email set in cookie) then he should redirect to "dashboard" page,How can i do this? I tried with following code but not working for me, giving me error ",Here is my current code

cookies returned from getServerSideProps Reason: undefined cannot be serialized as JSON

export async function getServerSideProps(context: { req: { headers: { cookies: any; }; }; }) {
    
  const cookies = context.req.headers.cookies;
  if (cookies && cookies.email) {
    // email is present in cookies, so redirect to /dashboard
    return {
      redirect: {
        destination: "/dashboard",
        statusCode: 302, // temporary redirect
      },
      props: {},
    };
  }
  
  return {
    props: {
      cookies,
    },
  };
}

When returning props.cookies from getServerSideProps , you are potentially returning the cookies as undefined . Use '' as the default value if missing.

You can do this:

  return {
    props: {
      cookies: cookies || '',
    },
  };

You need to parse the cookies and you can get the cookies on the request you don't need the header

const cookies = JSON.parse(context.req.cookies);
if(cookies.email !== undefined)... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM