a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

Overview

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense ready). I noticed how this code and route pattern was used on most of my projects and it was decided to convert it into a reusable package, that would probably meet most of the routing requirements without a lot of boilerplate.

Note: react-router-dom version >= 6 is required

Getting Started

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

// routes.tsx

import React from 'react';
import { IRoutesConfig } from 'auth-react-router';
import LoginPage from '../pages/LoginPage.tsx';

// public lazy loaded pages
const LazyPublicPage = React.lazy(() => import('../pages/PublicPage.tsx'));

// private lazy loaded pages
const LazyPrivatePage = React.lazy(() => import('../pages/PrivatePage.tsx'));
const LazyProfilePage = React.lazy(() => import('../pages/ProfilePage.tsx'));


export const routes: IRoutesConfig = {
  publicRedirectRoute: '/profile', // redirect to `/profile` when authorized is trying to access public routes
  privateRedirectRoute: '/login', // redirect to `/login` when unauthorized user access a private route
  defaultFallback: <MyCustomSpinner />,
  public: [
    {
      path: '/public',
      component: <LazyPublicPage />,
    },
    {
      path: '/login',
      component: <LoginPage />,
    },
  ],
  private: [
    {
      path: '/private',
      component: <LazyPrivatePage />,
    },
    {
      path: '/profile',
      component: <LazyProfilePage />
    },
  ],
  common: [
    {
      path: '/',
      component: <p>common</p>,
    },
    {
      path: '*',
      component: <p>page not found 404</p>,
    },
  ],
};

Link the defined above routes using AppRouter component

import { AppRouter, Routes } from 'auth-react-router';
import { BrowserRouter } from 'react-router-dom';
import { routes } from './routes';

export const App = () => {
  const { isAuth } = useAuthProvider();
  return (
    <BrowserRouter>
      <AppRouter isAuth={isAuth} routes={routes}>
        {/* Wrap `Routes` component into a Layout component or add Header */}
        <Routes />
      </AppRouter>
    </BrowserRouter>
  );
};

That is it, super easy!

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

Router / Routes basic configuration

AppRouter Provider interface

export interface IRouterContextProps {
  /** routes configuration */
  routes: IRoutesConfig;

  /** authorization state of the user, if not provided only `common` routes will work correspondingly */
  isAuth?: boolean;
}

routes configuration interface

export interface IRoutesConfig {
  /**
   * defaults to `/`
   * authorized users on public routes will be redirected to this route
   */
  privateRedirectRoute?: string;

  /**
   * defaults to `/`
   * unauthorized users on private routes will be redirected to this route
   */
  publicRedirectRoute?: string;

  /** default fallback component for lazy loaded route components */
  defaultFallback?: React.ReactElement;

  /** private routes are accessible only by authorized users */
  private?: IRoute[];

  /** public routes are accessible only by unauthorized users */
  public?: IRoute[];

  /** common routes are accessible only by authorized and unauthorized users */
  common?: IRoute[];
}

single route interface IRoute

export interface IRoute {
  /** a valid react-router-dom v6 path */
  path: string;

  /** the component to be rendered under the path */
  component: React.ReactElement;

  /**
   * if route component is lazy loaded using React.lazy() a fallback loading / spinner component can be specified
   * it has higher priority then the `defaultFallback` component
   * */
  fallback?: React.ReactElement;
}
You might also like...
Redux bindings for React Router – keep your router state inside your Redux store

redux-router This project is experimental. For bindings for React Router 1.x see here In most cases, you don’t need any library to bridge Redux and Re

Custom hook for tracking client-side navigation performance in Remix/React-Router applications
Custom hook for tracking client-side navigation performance in Remix/React-Router applications

remix-use-spa-metrics Custom hook for tracking client-side navigation performance in Remix/React-Router applications Motivation The current performanc

A simple and safe router for React and TypeScript.

A simple and safe router for React and TypeScript.

A simple and safe router for React and TypeScript.

@swan-io/chicane A simple and safe router for React and TypeScript. Design principles Typed routes: improving the DX, and making sure all your params

Render isomorphic React + React Router apps and components in Node

Render isomorphic React + React Router apps and components in Node

A custom React router that leverages the Web Animations API and CSS animations.
A custom React router that leverages the Web Animations API and CSS animations.

A custom React router that leverages the Web Animations API and CSS animations.

Route Sphere - Sync query parameters with a MobX store and React Router

Route Sphere - Sync query parameters with a MobX store and React Router

VSCode extension to generate a router based on file based routing and nested layouts

vscode-router-generator VSCode Extension to generate a router based on a file structure and returning the correct nested layouts. There can be optiona

Automatic breadcrumbs for React-Router

React Breadcrumbs React component use to generate a breadcrumb trail (compatible with React Router). Installation npm install --save react-breadcrumbs

Comments
  • Modal - React Router implementation

    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), []);
    }
    
    opened by amarmechai 2
Releases(0.4.7)
πŸ„β€β™‚οΈ The easiest way to slide React routes

react-slide-routes ??‍♂️ The easiest way to slide React routes Fit React Router v6 For React Router v5, please use [email protected] Add yarn a

ε—ε°εŒ— 63 Dec 24, 2022
named routes for react-router and your react application

react-router-namesake Example import { Switch } from "react-router"; import { BrowserRouter, Route, Link } from "react-router-dom"; import { Router as

Joe Hsu 6 Aug 12, 2021
React router that supports rendering of multiple independent (auxiliary) routes.

aux-router React router that supports rendering of multiple independent (auxiliary) routes. Install npm install --save aux-router Documentation AuxRou

Kamil Bugno 20 Oct 4, 2021
You can found the concept of react hooks, local storage, conditional rendering and react-router-dom.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Tikaram Acharya 2 Jun 1, 2022
Frontend of agro rent app built with React, Axios, React-router-dom v6 & Bootstrap

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: ya

Anuj Sharma 1 Dec 8, 2021
React app with TypeScript - React Router Dom

React Project with - React Router Dom My name is Alex Principe. I'm a Full stack developer who shares programming code with the community. This repo c

Alex Principe 2 Sep 20, 2022
🌎A react-router-dom adapter for Electron apps

Electron Router DOM ??A react-router-dom adapter for Electron apps If you've already tried using react-router-dom with Electron, had difficulties ge

Dalton Menezes 63 Dec 31, 2022
Generated file-based routes for React Location and Vite

Generouted Generated file-based routes for React Location and Vite Motivation I enjoyed working with file-based routing since started using it with Ne

Omar Elhawary 152 Dec 22, 2022
Provides drilldown-style horizontal slide transitions between index and child routes

This is a simple component that provides drilldown-style horizontal slide transitions between index and child routes.

null 12 Feb 28, 2022
:tada: Redux First History - Redux history binding support react-router - @reach/router - wouter

redux-first-history Redux First History - Make Redux 100% SINGLE-AND-ONLY source of truth! Redux history binding for react-router @reach/router wouter

Salvatore RavidΓ  367 Dec 31, 2022