1

I want to navigate to a Page only through button click on some other page and not through typing direct url route in browser in Next JS. Page is static and unauthenticated.

Rafa
  • 153
  • 1
  • 9
  • so you want to allow only authenticated users to navigate to the page and restrict unauthorised users from directly typing the url . Is that correct? – Ishan Bassi Sep 24 '21 at 08:30
  • authenticated or unauthenticated i want them not to be able to access page through url but only through clicking button on some other page – Rafa Sep 24 '21 at 11:22

1 Answers1

1

To achieve this , you have to use getServerSideProps. In getServerSideProps a request object is passed on every request. In the request object referer header is available which contains address of the page making the request.

Note that referer header in only available when user comes to specific page through a link. The header is not availabe when url is directly typed in search bar.

You can do something like this:

export async function getServerSideProps ({ params , req  }) {
  const post = await githubCms.getPost(params.slug)  
  const referer  =  req.headers.referer || null
  


  return {
    props: {
      post , referer
    }
  }
}

Now you can pass referer prop to your component and can change your rendering logic.

Important: Note that when you refreshes your page the referer becomes null . So you need to check if someone refreshes the page logic or you have to store the referer in local storage

Ishan Bassi
  • 490
  • 1
  • 5
  • 13