31rhcp
31rhcp

Reputation: 107

Prevent navigation to certain pages/routes

I have a Next.js (fix may not necessarily have anything to do with Next.js) app that I want to limit some navigation. This page in the Next.js docs mentions "you should guard against navigation to routes you do not want programmatically", but I'm unsure how to do this. Let's say I have the following pages:

/bikes
/boats
/cars

and I only want to allow a user to see /bikes. How would I be able to do this. I'm able to redirect from an undesired page to an acceptable page, but only after the undesired page loads. Is there a way to redirect before this (maybe by changing the URL as soon as it is changed)?

Upvotes: 1

Views: 3198

Answers (1)

Ed Hill
Ed Hill

Reputation: 26

I appreciate that this is an old question, however, I wish I had known this answer to it earlier than I did, so I would like to answer it for the record.

Our next.js app had a relatively complex set of permissions associated with accessing each page (with the ability to access the page, or different data presented on it) based on the authentication status of a user as well as the authorization scopes granted to them.

The solution that we used was the to return a redirect from getServerSideProps(). Normally one would return something like the following:

const getServerSideProps = (context) => {
  return {
    props: {
      myProp: 1
    }
  };
}

However, it is also possible to return a redirect. This redirect is performed on the server side prior to the page content being sent to the browser:

const getServerSideProps = (context) => {
  return {
    redirect: '/login'
  };
}

This is relatively new functionality - it was only pulled in towards the end of last year, and there isn't much documentation for it anywhere, but it perfectly serves this use case.

Upvotes: 1

Related Questions