GithubHelp home page GithubHelp logo

nichitaa / auth-react-router Goto Github PK

View Code? Open in Web Editor NEW
17.0 3.0 4.0 430 KB

A simple yet extensible approach for configuring and handling protected and role based routing for react applications using react-router-dom v6

Home Page: https://www.npmjs.com/package/@nichitaa/auth-react-router

License: MIT License

TypeScript 98.39% JavaScript 1.61%
react-router-dom-v6 routing context-api npm-package auth-route common-route

auth-react-router's Introduction

@nichitaa/auth-react-router is a lightweight package that uses and extends basic react-router-dom v6 functionality and allows you to define the routes based on user authorized and roles states. It provides a simple API for configuring public, private and common routes, and it has a simple and advance RBAC configuration.

Documentation (typedoc)

This code and routing pattern is used on most of my personal projects and would probably meet most of the routing requirement for any other react application, but beware and use it at your own risk.

Getting Started ๐ŸŽ‰

Peer Dependencies ๐Ÿ”จ

  • react: >=16,
  • react-dom: >=16,
  • react-router-dom: ^6.x

Installation โœจ

npm install @nichitaa/auth-react-router

Example

Define your application routes *(easier to maintain if are in separate file)

// src/routes.tsx
import { RoutesConfig } from '@nichitaa/auth-react-router';
import { Outlet } from 'react-router-dom';
import { lazy } from 'react';

/**
 * using normal `imports` or `lazy`
 */
import PageA from '../pages/LoginPage.tsx';

const LazyPageB = lazy(() => import('../pages/PageB'));
const LazyPageC = lazy(() => import('../pages/PageC'));
const LazyPageD = lazy(() => import('../pages/PageD'));

/**
 * optionally define roles (if you want to use RBAC functionality)
 */
export const roles = {
  ADMIN: 'ADMIN',
  OPERATION: 'OPERATION',
  MANAGER: 'MANAGER',
  REGULAR: 'REGULAR',
} as const;


/** routes definition */
export const routes: RoutesConfig = {
  /**
   * globally configured fallbacks (can be configured at route level too)
   */
  fallback: {
    /**
     * if user is on private route and has `authorized: false`, then he probably should be redirectied to a public route
     * and vice-versa, if those route fallbacks are not provided, default one is first common route (common[0].path)
     */
    privateRoute: '/b', 
    publicRoute: '/c',
    InvalidRoles: route => <GlobalInvalidRoute {...route} />,
    Suspense: <>...loading page...</>,
  },
  /**
   * common routes (accessible by all users)
   */
  common: [
    {
      path: '/',
      element: <>Route available for all users</>,
    },
    {
      path: '*',
      element: <p>PAGE NOT FOUND 404</p>,
    },
  ],
  /**
   * public paths (accessible only by users with `authorized: false`)
   */
  public: [
    {
      path: '/b',
      // with <Outlet/>
      element: <>
        <CustomLayout>
          <Outlet />
        </CustomLayout>
      </>,
      // nested routes
      routes: [
        {
          index: true,
          element: <LazyPageB />,
        },
        {
          path: ':id',
          element: <LazyPageC />,
        },
      ],
    },
  ],
  /**
   * private paths (accessible only by users with `authorized: true`)
   */
  private: [
    {
      path: '/c',
      element: <>Private page protected by all roles</>,
      roles: [roles.ADMIN, roles.MANAGER],
      allRolesRequired: true,
    },
    {
      path: '/c',
      element: <>Private page protected by at least one role</>,
      roles: [roles.OPERATION, roles.MANAGER],
    },
    {
      path: '/d',
      element: <LazyPageD />,
      roles: [roles.OPERATION, roles.MANAGER],
      // Private route with its own fallbacks
      fallback: {
        Suspense: <>...loading page for private route /d...</>,
        InvalidRoles: (route) => <>:( could not access route /d</>,
        /**
         *  fallback route if unauthroized user tryies to access `/d` route,
         *  usually you'd want to redirect him to a public/common page (a page that he has access to)
         */
        route: '/b',
      },
    },
  ],
};

Configure AuthReactRouter and render RoutesRoot

import { AuthReactRouter, RoutesRoot } from '@nichitaa/auth-react-router';
import { BrowserRouter } from 'react-router-dom';
import { routes, roles } from './routes';

export const App = () => {
  const { isAuthorized, userRoles } = useAuthProvider();
  return (
    <BrowserRouter>
      <AppRouter authorized={isAuthorized} routes={routes} roles={userRoles}>
        <RoutesRoot />
      </AppRouter>
    </BrowserRouter>
  );
};

To add a new route just add it to public, private or common array and it will work.

auth-react-router's People

Contributors

amarmechai avatar github-actions[bot] avatar nichita-pasecinic avatar nichitaa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

auth-react-router's Issues

Modal - React Router implementation

can we integrate Modal routes with this project?

Reference : Create contextual modal navigation with React Router V6

IRoute

export interface IRoute {
  ...

  modal?: boolean;
}

We can use this method de get all modal routes

const getModalRoutes = (routes: IRoute[]) => {
  return routes
    .map(route => {
      let modalRooutes: IRoute[] = [];
      const { children, ...rest } = route;

      if (rest.modal)
        modalRooutes.push(rest);

      if (children)
        modalRooutes.push(...getModalRoutes(children));

      return modalRooutes;
    })
    .reduce((accumulator, value) => accumulator.concat(value), []);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.