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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mohanmaali/react-auth-manager

v1.0.4

Published

Modern, secure, backend-agnostic React authentication library

Readme

@mohanmaali/react-auth-manager

npm version License: MIT

Simple authentication library for React applications.

Features

  • Works with any backend API
  • Automatic token refresh
  • Multiple storage options (cookie, localStorage, memory)
  • Easy to use hooks
  • Axios support

Installation

npm:

npm install @mohanmaali/react-auth-manager

yarn:

yarn add @mohanmaali/react-auth-manager

pnpm:

pnpm add @mohanmaali/react-auth-manager

Quick Start

Step 1: Configure Authentication

Create a file to configure your authentication:

// authConfig.js
export const authConfig = {
  login: async ({ email, password }) => {
    const response = await fetch("https://api.example.com/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    });
    return response.json(); // Returns: { accessToken, refreshToken }
  },

  getUser: async (accessToken) => {
    const response = await fetch("https://api.example.com/me", {
      headers: { Authorization: `Bearer ${accessToken}` },
    });
    return response.json(); // Returns user data
  },

  refresh: async () => {
    const response = await fetch("https://api.example.com/refresh", {
      method: "POST",
    });
    return response.json(); // Returns new tokens
  },

  logout: async () => {
    await fetch("https://api.example.com/logout", {
      method: "POST",
    });
  },

  tokenStorage: "cookie", // Options: "cookie", "localStorage", "memory"
};

Step 2: Setup Provider

Wrap your application with AuthProvider:

// App.js
import { AuthProvider } from "@mohanmaali/react-auth-manager";
import { authConfig } from "./authConfig";

function App() {
  return (
    <AuthProvider config={authConfig}>
      <YourApp />
    </AuthProvider>
  );
}

export default App;

Step 3: Use in Components

import { useAuth } from "@mohanmaali/react-auth-manager";

function LoginPage() {
  const { login, isLoading } = useAuth();

  const handleLogin = async () => {
    await login({
      email: "[email protected]",
      password: "password123",
    });
  };

  return (
    <button onClick={handleLogin} disabled={isLoading}>
      {isLoading ? "Loading..." : "Login"}
    </button>
  );
}

Usage Examples

Login Form

import { useState } from "react";
import { useAuth } from "@mohanmaali/react-auth-manager";

function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { login, isLoading, error } = useAuth();

  const handleSubmit = async (e) => {
    e.preventDefault();
    await login({ email, password });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button type="submit" disabled={isLoading}>
        {isLoading ? "Logging in..." : "Login"}
      </button>
      {error && <p>{error.message}</p>}
    </form>
  );
}

Display User Info

import { useAuth } from "@mohanmaali/react-auth-manager";

function UserProfile() {
  const { isAuthenticated, user, logout, isLoading } = useAuth();

  if (isLoading) return <p>Loading...</p>;

  if (!isAuthenticated) return <p>Please log in</p>;

  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <p>Email: {user.email}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Protected Routes

import { useRequireAuth } from "@mohanmaali/react-auth-manager";

function AdminPage() {
  useRequireAuth(() => {
    window.location.href = "/login";
  });

  return <div>Admin Dashboard</div>;
}

Navigation Menu

import { useAuth } from "@mohanmaali/react-auth-manager";

function Navigation() {
  const { isAuthenticated, user, logout } = useAuth();

  return (
    <nav>
      <a href="/">Home</a>
      {isAuthenticated ? (
        <>
          <span>Hello, {user.name}</span>
          <button onClick={logout}>Logout</button>
        </>
      ) : (
        <a href="/login">Login</a>
      )}
    </nav>
  );
}

Axios Integration

Setup automatic token injection for Axios:

import axios from "axios";
import { setupAxiosInterceptors } from "@mohanmaali/react-auth-manager";

const api = axios.create({
  baseURL: "https://api.example.com",
});

setupAxiosInterceptors({
  axiosInstance: api,
  tokenStorage: "cookie",
  refresh: async () => {
    const response = await fetch("https://api.example.com/refresh", {
      method: "POST",
    });
    return response.json();
  },
});

export default api;

Now all requests will include the authentication token automatically:

// Tokens are added automatically
api.get("/user/profile");
api.post("/user/update", { name: "John" });

API Reference

useAuth Hook

const {
  isAuthenticated,  // Boolean: user is logged in
  isLoading,        // Boolean: authentication in progress
  user,             // Object: user information
  error,            // Object: any error occurred
  login,            // Function: login user
  logout,           // Function: logout user
  refreshToken,     // Function: manually refresh token
} = useAuth();

useRequireAuth Hook

useRequireAuth((callback) => {
  // Runs if user is not authenticated
});

Example:

useRequireAuth(() => {
  navigate("/login");
});

Token Storage Options

| Storage | Description | |---------|-------------| | cookie | Recommended. Most secure, protected from XSS attacks | | localStorage | Persists across browser sessions, less secure | | memory | Highest security but lost on page refresh |

Configuration

Your authConfig object should have:

| Property | Type | Required | Description | |----------|------|----------|-------------| | login | Function | Yes | Handles user login | | getUser | Function | Yes | Fetches user information | | refresh | Function | Yes | Refreshes authentication token | | logout | Function | Yes | Handles user logout | | tokenStorage | String | Yes | Where to store tokens: "cookie", "localStorage", or "memory" |

Troubleshooting

Tokens not saved after refresh?

  • Use tokenStorage: "cookie" or "localStorage" instead of "memory"

User logged out unexpectedly?

  • Check your refresh function is working correctly

CORS errors?

  • Add credentials: "include" in your fetch requests when using cookies

License

MIT License

Links


Made by Mohan Maali