How to protect routes that already exist in a next.js app without replicating getServerSideProps on all pages

Asked

Viewed 5 times

-1

I am mounting an authentication in an existing next.js app and need to protect the routes. The best way I found is by using cookie and the getServerSideProps method so that when a protected route is accessed directly by the url, the "flash" does not happen to show the route content and then redirect to login.

export const getServerSideProps: GetServerSideProps = async ctx => {
  const { 'totem-autoatendimento.token': token } = parseCookies(ctx);

  if (!token) {
    return {
      redirect: {
        destination: '/',
        permanent: false
      }
    };
  }

  return {
    props: {}
  };
};

The problem is having to replicate this method on all protected project routes (all are protected except '/' which is the login screen). I wonder if there’s a better way to do this on the server side

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.