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 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-auth-service

v0.0.2

Published

Reusable React **authentication library** with JWT handling, Axios interceptors, and routing helpers.

Readme

React Auth Service

Reusable React authentication library with JWT handling, Axios interceptors, and routing helpers.

⚠️ Routing and navigation are owned by the consumer app. This library provides UI, auth state, and API handling — not app routes.


Why this package?

Most apps repeat the same authentication logic:

  • Login & signup UI
  • JWT storage and refresh handling
  • Protecting routes
  • Attaching tokens to API calls

Auth UI centralizes this logic into a reusable package so consumer apps can focus on business features.


Features

  • 🔐 Login & Signup UI (AuthForm)
  • 👤 User profile UI (UserProfile)
  • 🧠 Central auth state via AuthProvider
  • 🛡️ Public & Protected route guards
  • 🔄 Axios interceptor with automatic token refresh
  • 🚫 Global session-expired handling

Installation

npm install react-auth-service

Required setup (important)

Auth Initialization (Mandatory for Consumer Apps) Purpose of initAuth()

initAuth() initializes the authentication service and configures the internal Axios instance with the backend API base URL.

This allows:

Dynamic backend URL configuration

Automatic token attachment

Refresh token handling

Environment-specific backend switching (local / QA / UAT / prod)

Without calling initAuth(), the auth service will not work.

⚠️ Mandatory Initialization Step

Before rendering the React application, the consumer app must call initAuth() exactly once.

✅ Correct Usage
import { initAuth } from 'react-auth-service';

await initAuth({
  apiBaseUrl: 'http://localhost:9000', // Backend running URL
});

1️⃣ Wrap your app with AuthProvider and BrowserRouter

import { BrowserRouter } from 'react-router-dom';
import { AuthProvider } from 'react-auth-service';

<BrowserRouter>
  <AuthProvider>
    <App />
  </AuthProvider>
</BrowserRouter>

BrowserRouter must be declared once in the consumer app.


Routing helpers

This package does not define routes. Instead, it provides helpers you can compose with your routes.

PublicRoute

Used for pages like Login / Signup.

  • Accessible only when user is not authenticated
  • Redirects authenticated users
<Route
  path="/"
  element={
    <PublicRoute redirectTo="">
      <AuthForm onLoginSuccess={login} />
    </PublicRoute>
  }
/>

ProtectedRoute

Used for private pages.

  • Blocks unauthenticated access
  • Redirects to login page
<Route
  path="/profile"
  element={
    <ProtectedRoute redirectTo="">
      <UserProfile onLogout={logout} />
    </ProtectedRoute>
  }
/>

Auth flow (how it works)

Login

  1. User submits login form
  2. Login API returns accessToken
  3. Token is stored in memory
  4. AuthContext updates auth state
  5. Consumer app handles navigation
setAccessToken(token);
localStorage.setItem('isLoggedIn', 'true');

Signup

  1. User submits signup form
  2. Password is validated on client
  3. Registration API is called
  4. User is redirected to login mode

Axios interceptor (core logic)

This package exports a preconfigured axiosInstance.

What it does

  • Attaches Authorization: Bearer <token> automatically
  • Skips auth headers for login & signup APIs
  • Refreshes token automatically on expiry
  • Queues failed requests during refresh
  • Logs out user if refresh fails

Usage in consumer app

import { axiosInstance } from 'react-auth-service';

axiosInstance.get('/api/orders');

You must use axiosInstance instead of raw Axios to get auth benefits.


Session expiration handling

If refresh token fails:

  • User is logged out
  • Session-expired flag is stored
  • App redirects to login page

On next load, AuthForm detects this and shows a session-expired message.


Auth state management

Auth state is managed via AuthContext.

const { isAuthenticated, login, logout } = useAuth();
  • State is persisted using localStorage
  • Token is cleared on logout
  • Context ensures route guards stay in sync

UserProfile component

  • Fetches user details on mount
  • Uses axiosInstance internally
  • Calls logout API on logout
  • Delegates navigation to consumer
<UserProfile onLogout={logout} />

Consumer responsibilities

The consumer app must:

  • Own routing and navigation
  • Provide backend APIs
  • Configure endpoints
  • Wrap app with AuthProvider
  • Use provided axiosInstance

This library does not:

  • Create routes
  • Handle databases
  • Manage backend authentication

Backend expectations

Your backend should provide:

  • POST /login → returns accessToken
  • POST /register
  • POST /refresh-token (cookie-based)
  • GET /user-details
  • POST /logout

JWT-based authentication is assumed.


Common mistakes

❌ Importing Axios directly instead of axiosInstance ❌ Wrapping BrowserRouter multiple times ❌ Using useAuth outside AuthProvider ❌ Expecting this package to control routing


Summary

Auth UI provides:

  • UI components
  • Auth state management
  • Secure API handling

You control:

  • Routing
  • Navigation
  • Backend

This separation keeps your app flexible, secure, and scalable.


License

MIT