react-router-guards

raw JSON →
1.0.2 verified Sat Apr 25 auth: no javascript maintenance

Provides a middleware API for React Router (v5), allowing developers to run guard functions between navigation and route rendering. Currently at version 1.0.2, it is stable but not actively maintained (last update 2019). Key features include GuardProvider and GuardedRoute components, support for meta data on routes, loading/error components, and TypeScript types. Unlike simple auth wrappers, it offers a full lifecycle with next() callbacks for redirects, async guards, and error handling.

error TypeError: Cannot read property 'redirect' of undefined
cause The 'next' parameter in guard function is undefined due to incorrect signature (using wrong parameter count or names).
fix
Define guard as (to, from, next) => ... and ensure exactly three parameters.
error Warning: React version mismatch. Expected >=16.8.0.
cause Installed package with React version older than 16.8.0 (hooks not supported).
fix
Update React to >=16.8.0 using 'npm install react@latest'.
error Module not found: Can't resolve 'react-router-dom'
cause Missing peer dependency react-router-dom.
fix
Install react-router-dom v5: 'npm install react-router-dom@5.0.0'.
deprecated Package last updated in 2019; compatible only with React Router v5, not v6.
fix Use react-router-dom v5 or consider migrating to React Router v6 with alternative guard solutions.
gotcha Guard functions must call next() exactly once; otherwise route may hang or render incorrectly.
fix Ensure every guard calls next() or next.redirect() in all code paths.
gotcha The 'loading' prop on GuardProvider should be a React component, not null or undefined when async guards are used.
fix Provide a loading component to avoid blank screen during async guard resolution.
npm install react-router-guards
yarn add react-router-guards
pnpm add react-router-guards

Sets up guard middleware with a loading component, an auth guard that redirects unauthenticated users, and meta data on routes.

import React from 'react';
import { BrowserRouter, Switch } from 'react-router-dom';
import { GuardProvider, GuardedRoute } from 'react-router-guards';

const Home = () => <div>Home</div>;
const Login = () => <div>Login</div>;
const Loading = () => <div>Loading...</div>;
const Error = () => <div>Error</div>;

const requireAuth = (to, from, next) => {
  const isLoggedIn = localStorage.getItem('token');
  if (to.meta.auth && !isLoggedIn) {
    next.redirect('/login');
  } else {
    next();
  }
};

function App() {
  return (
    <BrowserRouter>
      <GuardProvider guards={[requireAuth]} loading={Loading} error={Error}>
        <Switch>
          <GuardedRoute exact path="/login" component={Login} />
          <GuardedRoute exact path="/" component={Home} meta={{ auth: true }} />
        </Switch>
      </GuardProvider>
    </BrowserRouter>
  );
}

export default App;