Dayana Scott
Dayana Scott

Reputation: 31

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!

Upvotes: 3

Views: 1694

Answers (1)

asi hej
asi hej

Reputation: 333

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
  }
}

Upvotes: 2

Related Questions