简体   繁体   中英

How to create protected page in react nextjs

i am fairly new to nextjs. I am trying to create protected page for authorised users on my web app.

Does anyone have any thoughts on how to structure it? Thanks!

To answer you question, it depends. You can do it two ways:

Front end protection

When the page loads, show some kind of loading state. For example spinner. Meanwhile, checks if user is logged and if not, use next/router to redirect user to Login page (for example).

Server protection

For server protection, you can use getServerSideProps function. It can look something like this:

export async function getServerSideProps(context) {
  // fetch user logged state
  // check if user is logged
  // you can use server side redirection or pass "redirect" prop to 
  // the component and redirect on page load
  return {
    props: {}, // will be passed to the page component as props
  }
}

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