Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you deal with public and private routes in a NextJS app?

I'm working on a app that we have public and admin routes, in our past CRA app we've used custom routes elements, but we dont have thins in nextjs... We have a lot of public pages, and we have 20 private pages/routes.

Whats is the best way to deal with protected autenticated routes and public routes in nextjs?

Thanks so much! Best

like image 931
Wilson Neto Avatar asked Nov 03 '20 12:11

Wilson Neto


2 Answers

I personally have been using HOCs (higher-order component) for this.

Here is an example authentication HOC:

const withAuth = Component => {
  const Auth = (props) => {
    // Login data added to props via redux-store (or use react context for example)
    const { isLoggedIn } = props;

    // If user is not logged in, return login component
    if (!isLoggedIn) {
      return (
        <Login />
      );
    }

    // If user is logged in, return original component
    return (
      <Component {...props} />
    );
  };

  // Copy getInitial props so it will run as well
  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
};

export default withAuth;

You can use this HOC for any page component. Here is an example of usage:

const MyPage = () => (
  <> My private page</>
);

export default withAuth(MyPage);

You can extend withAuth HOC with role checks like public, regular user and admin if needed.

like image 180
AleXiuS Avatar answered Oct 16 '22 09:10

AleXiuS


Thanks a lot @AleXiuS for your answer ! I have mixed your solution and this great article for those who want to use this hoc with typescript :

import { NextComponentType } from "next";

function withAuth<T>(Component: NextComponentType<T>) {
  const Auth = (props: T) => {
    // Login data added to props via redux-store (or use react context for example)
    const { isLoggedIn } = props;

    // If user is not logged in, return login component
    if (!isLoggedIn) {
      return <Login />;
    }

    // If user is logged in, return original component
    return <Component {...props} />;
  };

  // Copy getInitial props so it will run as well
  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
}

export default withAuth;
like image 28
Putxe Avatar answered Oct 16 '22 08:10

Putxe