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...

Utilities library built on top of Next.js providing feature extensions and helpers for common patterns

nextjs-utilites This library provides many helpful utilities for use in Next.js projects. Prerequisites This project requires NodeJS (version 8 or lat

Sep 7, 2022

React features to enhance using Rollbar.js in React Applications

Rollbar React SDK React features to enhance using Rollbar.js in React Applications. This SDK provides a wrapper around the base Rollbar.js SDK in orde

Jan 3, 2023

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Jan 4, 2023

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles.

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles. If you're tired of fighting some other developer's CSS and DOM structure, this carousel is for you.

Dec 24, 2021

A plugin that lets you override the Webpack modules public path in webpage runtime.

dynamic-public-path-plugin A plugin that lets you override the Webpack modules public path in webpage runtime. plugin : webpack-runtime-public-path-pl

Jan 25, 2022

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

react-admin A frontend Framework for building data-driven applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Materi

Dec 30, 2022

React components and hooks for creating VR/AR applications with @react-three/fiber

React components and hooks for creating VR/AR applications with @react-three/fiber

@react-three/xr React components and hooks for creating VR/AR applications with @react-three/fiber npm install @react-three/xr These demos are real,

Jan 4, 2023

React-Mini-Projects - Simple React mini-applications

React Mini Projects A Fully Responsive React Application contain these mini apps : Todo App Movie App Budget App Flash Card App Factor App This app wa

Jan 1, 2022

Bdc-walkthrough - An Angular Material library for displaying walk-through pop-ups and dialogs using a declarative way.

Bdc-walkthrough - An Angular Material library for displaying walk-through pop-ups and dialogs using a declarative way.

Material walk-through library An Angular Material library for displaying walk-through pop-ups and dialogs using a declarative way. Show Demo Prerequis

Dec 14, 2022
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)
🔄 Basic project to start studying React and Typescript. With it you can translate text to binary or morse language. This project addresses the creation of routes and components.

max-conversion Projeto criado para iniciar nos estudos de React e Typescript Basic project to gain knowledge in react Na plataforma é possível convert

Igor Neves 3 Feb 12, 2022
A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router.

A web application to search all the different countries in the world and get details about them which can include languages, currencies, population, domain e.t.c This application is built with CSS, React, Redux-Toolkit and React-Router. It also includes a theme switcher from light to dark mode.

Franklin Okolie 4 Jun 5, 2022
Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose.

spa-store Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose. Contributing Feedback Roadmap Releases Check

Luis Falcon 2 Jul 4, 2022
Basic React Project with React Router, ContextAPI and Login

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

null 26 Jan 3, 2023
Tina is an open source editor that brings visual editing into React websites. Tina empowers developers to give their teams a contextual and intuitive editing experience without sacrificing code quality.

Tina is an open-source toolkit for building content management directly into your website. Community Forum Getting Started Checkout the tutorial to ge

Tina 8.2k Jan 1, 2023
A weather app done with React. Allows you to make a search for the current weather by simply typing "common knowledge" cities and save them to favourites on local storage.

Simpliest Weather React-App A weather app done with React. Allows you to make a search for the current weather by simply typing "common knowledge" cit

Larry Noriega 3 Aug 24, 2022
Material-UI is a simple and customizable component library to build faster, beautiful, and more accessible React applications. Follow your own design system, or start with Material Design.

Material-UI Quickly build beautiful React apps. Material-UI is a simple and customizable component library to build faster, beautiful, and more access

Material-UI 83.6k Dec 30, 2022
Common React Native components used by "Roqay" packed in library for usage in future projects.

Roqay Common React Native Components Common React Native components used by Roqay packed in library for usage in future projects. Installation yarn ad

RoQay 3 Feb 10, 2022
Cloudflare Durable Objects + Itty Router = shorter code

TLDR; Cloudflare Durable Objects + Itty Router = much shorter code Features Removes nearly all boilerplate from Durable Objects Run instance methods d

Kevin R. Whitley 156 Jan 4, 2023
Common recipes to productively use Nx with various technologies and in different setups. Made with ❤️ by the Nx Team

Nx Recipes Welcome to Nx Recipes! Here you'll find various examples to use Nx to achieve a particular goal. Contributing Absolutely!! We're going to h

Nrwl 30 Dec 24, 2022