# Route Management

Route protection means, protecting any route from unauthorized access. For example, sign-in or signup pages are public pages and any user can access them. However there are many pages that only authenticated users can access, those paths are called protected routes. In Crema, we have provided the functionality of route protection.

Mainly in Crema, we have three different types of the route structure as below described

1. **Authorized Route:**\
   In this type of structure, we mainly add the authenticated routes that can access based on the authentication of a particular role of the user or any role of the authenticated user. \
   \
   We have a key named "fallbackPath" for this structure. It takes a URL. This "fallbackPath" key is used to redirect the user to this path/URL in case the user is not authenticated or not logged in.\
   \
   We have another key named "unAuthorizedComponent" for this structure. It takes a component, we use this component to show it to the user if the user is not satisfied with the authorization condition of the route.<br>

   <pre class="language-javascript"><code class="lang-javascript"><strong>const authorizedStructure = {
   </strong><strong>  fallbackPath: '/signin',
   </strong>  unAuthorizedComponent: &#x3C;Error403 />,
     routes: [
       ...accountPagesConfigs,
       ....
     ]
   }
   </code></pre>

2. **Un-Authorized Route:**\
   In this type of structure, we mainly add the auth routes of the user. like signin, signup and forgetting password

   ```javascript
   const unAuthorizedStructure = {
     fallbackPath: initialUrl,
     routes: authRouteConfig,
   };
   ```

3. **Anonymous Route**\
   In this category general-purpose pages come. these page doesn't belong to the user's authorization state. like 404, 500, maintenance, coming soon etc

   <pre class="language-javascript"><code class="lang-javascript">const anonymousStructure = {
   <strong> routes: errorPagesConfigs.concat([
   </strong>    {
         path: '/',
         element: &#x3C;Navigate to={initialUrl} />,
       },
       {
         path: '*',
         element: &#x3C;Navigate to="/error-pages/error-404" />,
       },
     ]),
   };
   </code></pre>

Using the above three types of routes we will manage the crema hole routing system like below. By using these three types of the routes structure we will generate the route dynamically

```javascript
// Route Generator Sample

import { useRoutes } from 'react-router-dom';
import { useAuthUser } from '@crema/hooks/AuthHooks';
import generateRoutes from '@crema/helpers/RouteGenerator';


  const { user, isAuthenticated } = useAuthUser();
  const generatedRoutes = generateRoutes({
    isAuthenticated: isAuthenticated,
    userRole: user?.role,
    unAuthorizedStructure,
    authorizedStructure,
    anonymousStructure,
  });

  const routes = useRoutes(generatedRoutes);// this will return the routes array
```

### Create a new route

To create a new route, We need to follow two steps as below.\
\
**Step 1. (Add Sidebar Menu):** To allow access to the navigation menu for a particular user role. you need to go to the `apps/{projectName}/src/core/AppRoutes/routeConfig.js` file, In this file, we declared all the navigation(route) menus. We want to bind the particular menu with the user role then we assign the role to the route menu.

While we assign a role to the route menu, you have to pass one extra property named "**permittedRole**" in the menu object in order to make the menu protected based on the user role.

{% hint style="info" %}
Don't need to add those routes in this config file that don't belong to the left sidebar
{% endhint %}

```javascript
//Any user can access this menu
const routesConfig = [
   ...,
   {
     id: 'account',                             // Id of the Menu
     title: 'Account',                          // Title of the Menu 
     messageId: 'sidebar.pages.extraPages.account',// Locale id of the Menu
     type: 'item',                              // Type of menu of the Menu 
     icon: <MdOutlineManageAccounts />,         // Icon of the menu navigation
     url: '/account',                           // Path of the menu navigation
   },
   ...
 ]



//The user has Staff level permission can access this menu
const routesConfig = [
   ...,
   {
     id: 'account',                              // Id of the Menu
     title: 'Account',                           // Title of the Menu 
     messageId: 'sidebar.pages.extraPages.account',// Locale id of the Menu
     type: 'item',                               // Type of menu of the Menu 
     permittedRole: RoutePermittedRole.Staff      // Permitted user roles of the Menu
     icon: <MdOutlineManageAccounts />,          // Icon of the menu navigation
     url: '/account',                            // Path of the menu navigation
   },
   ...
 ]
   

///The user has Staff and Admin level permission can access this menu
  
const routesConfig = [
    ...,
    {
     id: 'account',                              // Id of the Menu
     title: 'Account',                           // Title of the Menu 
     messageId: 'sidebar.pages.extraPages.account',// Locale id of the Menu
     type: 'item',                               // Type of menu of the Menu 
     permittedRole: [                            // Permitted user roles of the Menu
        RoutePermittedRole.Staff,                 // This is an optional property
        RoutePermittedRole.Admin
        ], //
     icon: <MdOutlineManageAccounts />,          // Icon of the menu navigation
     url: '/account',                            // Path of the menu navigation
   },   
   ...
]  
```

**Step 2. (Add new Route):** We need to create a route and need to define its protection based on our requirements in the `apps/source/src/core/AppRoutes` directory. Don't forget to assign this to one of the route structures *\[authorizedStructure /unAuthorizedStructure/anonymousStructure]* based on our requirements.

To protect the route from unwanted access,  we need to add the '**permittedRole**' property to the route, this will be protected the route base on the user's roles. Ex in the below code snip&#x73;**,** We are assigning three different types of access to the route.&#x20;

```javascript
import React from 'react';
import { RoutePermittedRole } from '@crema/constants/AppEnums';
import Account from '../../modules/account/MyProfile';

//Non-restricted routes any User can access it
export const accountPagesConfigs = [// No need to pass permittedRole for public routes
  {
    path: '/account',
    element: <Account />,
  },
];


//Restricted routes allowed for user's Staff role only
export const accountPagesConfigs = [
  {
    permittedRole: RoutePermittedRole.Staff,
    path: '/account',
    element: <Account />,
  },
];

//Restricted routes allowed for the multiple roles of user's like Admin and Staff 
export const accountPagesConfigs = [
  {
    permittedRole: [RoutePermittedRole.Admin, RoutePermittedRole.Staff],
    path: '/account',
    element: <Account />,
  },
];
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cremawork.com/v-4/decelopment/route-management.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
