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
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With