npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-auth-navigation

v1.2.1

Published

React library for authenticated routes

Downloads

9

Readme

react-auth-navigation

React library for authenticated routes

NPM JavaScript Style Guide

Install

// with npm
npm i react-auth-navigation

// with yarn
yarn add react-auth-navigation

Why is react-auth-navigation ?

It is a react library built on top of react-router-dom. React Auth Navigation provides us to create an authenticated routes and manages all the complicated routing and authenticating the users in client-side.

Usage

Navigation

Before we dive into creating authenticated routes, we should have some concept of public, private and protected routes.

But, What exactly are public, private and protected routes ?

  • Public Routes are those routes which can be accessed with or without login.
  • Private routes are those routes which cannot be accessed without login.
  • Protected routes are those types of public routes which cannot be accessed if a user is logged in.

Now Lets create authenticated routes.

withNavigation()

withNavigation() is responsible for managing all routes and userRoles. withNavigation() hoc should be exported from root component. It accepts Component as first argument and Configuration Object as second argument.

Let us configure the second argument.

  • routerType ( optional ) : It can be either "hash" or "browser". Default "browser".

  • publicPaths accepts an array of object with following keys:

    • key ( string ) ( optional ) : Defines unique key for each navigation route.
    • name ( string ) : Defines the name for a path and used as a routes key for useNavigation() hook keys if key is not passed.
    • path ( string ) : Defines the path for a component.
    • component ( Component ) : Defines a component for a path.
    • restricted ( boolean ) : If true then it is protected route otherwise public.
    • subPaths ( array ) ( optional ) : Accepts array of object with same as publicPaths array. It is used to make sub routes ( full-page routing ).
    • nestedPaths ( array ) ( optional ) : Accepts array of object with same as publicPaths array. It is used to make nested routes ( component routing ).
    • props ( any ) ( optional ) : Defines the props for each route keys.
  • privatePaths accepts an array of object with following keys:

    • key ( string ) ( optional ) : Defines unique key for each navigation route.
    • name ( string ) : Defines the name for a path and used as a routes key for useNavigation() hook keys if key is not passed.
    • path ( string ) : Defines the path for a component.
    • component ( Component ) : Defines a component for a path.
    • subPaths ( array ) ( optional ) : Accepts array of object with same as publicPaths array. It is used to make sub routes ( full-page routing ).
    • nestedPaths ( array ) ( optional ) : Accepts array of object with same as publicPaths array. It is used to make nested routes ( component routing ).
    • props ( any ) ( optional ) : Defines the props for each route keys.
  • userRoles is used to define the access routes for a particular user roles. accepts an object with following format:

    ...
    userRoles: {
        ...
        [userRole: string] : { access: Array<string> }
    }

Example

Basic example of routing.

First create publicPaths, privatePaths and userRoles.

// routes.js

import Page1 from "./Pages/Page1";
import Page2 from "./Pages/Page2";

export const publicPaths = [
  {
    name: "Public",
    path: "/public",
    component: Page1,
    restricted: true,
  },
];

export const privatePaths = [
  {
    name: "Private",
    path: "/private",
    component: Page2,
  },
];

export const userRoles = {
  user: { access: ["/public"] },
  admin: { access: ["*"] }, // '*' defines to give access to all paths.
};

Now lets use this with withNavigation() hoc.

// app.js
import React from "react";
import { withNavigation } from "react-auth-navigation";
import { publicRoutes, privateRoutes, userRoles } from "./routes";

const App = () => {
  return (
    // ...
  );
};

export default withNavigation(App, {
  publicPaths,
  privatePaths,
  userRoles,
});

And that's it. Its all you should do to define the routes and user-roles.

Auth

Auth provides 2 different HOCs which handles all the authentications defined by withNavigation() HOC.

Auth

It lets you define the current state of a user i.e. ( logged state and logged role ) and allows us to define global state which can be accessed from any component with useAuth() hook.

It accepts two props:

  • config ( object )

    You must pass an config object to config prop. Object should be of following shape :

    • isLoggedIn ( boolean ) : Defines logged state of a user.
    • userRole ( string ) : Defines current role of a user.
  • state ( object )

    It can be used as a global state which can accept any object with any keys.

Auth.Screens

It returns all the authenticated screens based on the current state of a user and all the routes provided to withNavigation() HOC. Component with Auth.Provider hoc should be wrapped with withNavigation() hoc.

It can accepts one optional prop:

  • path ( string ) ( optional )

It is required for nested routes. By default its value is taken as null or '/';

Auth.Screens hoc should be wrapped inside Auth hoc.

Example

// app.js
import { withNavigation, Auth } from "react-auth-navigation";
import { publicPaths, privatePaths, userRoles } from "./routes";

const App = () => {
  const [config, setConfig] = useState({ isLoggedIn: false, userRole: "user" });

  return (
    <Auth
      config={config}
      state={{
        logout: () => {
          setConfig({ isLoggedIn: false, userRole: "user" });
        },
      }}
    >
      <Auth.Screens />
    </Auth>
  );
};

export default withNavigation(App, {
  publicPaths,
  privatePaths,
  userRoles,
});

useNavigation()

useNavigation() is a hook which gives access to the navigation object providing you to navigate between different screens, providing you all accessible routes according to the current state of a user ( logged state and logged role ). It is also very useful for a component which is not directly a route defined in public or private paths because it doesn't have access to history prop directly.

useNavigation() returns an object with the following properties :

  • navigation ( object )

    Object for handling navigation and provides all authenticated routes name and path.

    • routes ( object ) : Object with name key you defined in publicPaths and privatePaths in withNavigation() and values are the object of name and path for a defined key.
    • navigate ( string ) : Function which takes either string or an object similar to react-router-dom’s history.push() function.
    • goBack ( function ) : Function which will navigate to the previous screen.
    • goForward ( function ) : Function which will navigate to the next screen if history is available.
  • history ( object ) : History object same as react-router-doms's history object.

  • location ( object ) : Location object same as react-router-dom's location object.

  • params ( object ) : Params object same as react-router-dom's params object.

Example

import { useNavigation } from "react-auth-navigation";

const { navigation, history, location, params } = useNavigation();

useAuth()

useAuth() is a hook which gives access to the config object and state object defined in hoc directly. By default it returns an object with isLoggedIn, userRole and all the keys passed inside the state object.

Example

import { useAuth } from "react-auth-navigation";

export default function() {

    // config and state can be accessed with useAuth()
    const { isLoggedIn, userRole, logout } = useAuth();

    return () {
        // ...
    }
}

License

MIT © dipeshrai123