Route Protection

Route protection with Next.js

Route protection means protecting any defined path from unauthorized access. For example, Signin or Signup pages are common paths/unrestricted paths and any user can access it. However there are many paths or pages that only logged in users can access, those paths are called Protected Routes. In Crema, we have provided the functionality of route protection, you have to follow the following steps to protect the route:- Step 1. To hide/show the menu based on the user role, We need to protect the navigation menu as well as routes. To protect the navigation menu go to the src/modules/routesConfig.js file, In this file, we declared all the navigation(route) menu. We want to bind the menu with the auth role of the user. then we assign the role to the route menu.

While defining the route menu, you have to pass one extra property named "auth" in the menu object in order to make the menu protected like below.

Step 2. If we want to protect our route then Crema Provide 2 different-2 HOC as following

  • AppPage HOC is for protecting the route. In case you want to protect your route then you need to wrap your component in this HOC as following.

    const HealthCare = asyncComponent(() => import('../../modules/dashboard/HealthCare'));
    export default AppPage(() => <React.Fragment>
      <PageMeta title="Health Care | Crema " />
  • DefaultPage HOC is for the default pages. This HOC is used for that route that doesn't have a sidebar and header by default like the login pages of Crema.

    const SignIn = asyncComponent(() => import('../modules/auth/Signin/index'));
    export default DefaultPage(() => <SignIn />);

Q: How I can access the dashboards as the default route without login(with the sidebar and header)?

Ans. To achieve this there are few steps to follow as following

  1. Make your own HOC for this kind of route. The following things need to keep in mind during writing the HOC i. We don't need to check the user is logged in or not. ii. We need to include the Layout and the layoutWrapper should look like the following

    export default (ComposedComponent) => (props) => {
      const {navStyle} = useContext(AppContext);
      const AppLayout = Layouts[navStyle];
      return (
          <ComposedComponent {...props} />

  2. Finally, you need to wrap your route with this HOC.

Last updated