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

@zhengliu92/react-auth-hook

v1.0.1

Published

A custom React hook library for managing authentication status

Readme

React Auth Hook

A lightweight React hook library for authentication with automatic token refresh and request management.

Demo GitHub npm

Features

  • 🔐 Simple authentication state management
  • 🔄 Automatic token refresh on expiration
  • 📡 Built-in authenticated requests with Bearer token
  • 💾 Persistent state with localStorage
  • 🎯 Full TypeScript support with generic response types
  • ⚡ Lightweight and performant

Installation

npm install @zhengliu92/react-auth-hook

Quick Start

1. Setup AuthProvider

import { AuthProvider } from '@zhengliu92/react-auth-hook';

const config = {
  login_url: 'https://api.example.com/auth/login',
  refresh_url: 'https://api.example.com/auth/refresh', // optional
  access_expiration_code: 401, // optional
};

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

2. Use the Hook and HTTP Client

import { useAuth, httpClient } from '@zhengliu92/react-auth-hook';

function LoginComponent() {
  const { login, logout, isAuthenticated } = useAuth();

  const handleLogin = async () => {
    try {
      await login({ email: '[email protected]', password: 'password' });
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  const fetchData = async () => {
    // httpClient automatically handles authentication and token refresh
    const response = await httpClient.get('/api/protected');
    console.log(response.data);
  };

  const createUser = async (userData) => {
    const response = await httpClient.post('/api/users', userData);
    console.log('User created:', response.data);
  };

  return isAuthenticated ? (
    <div>
      <button onClick={fetchData}>Fetch Data</button>
      <button onClick={() => createUser({ name: 'John' })}>Create User</button>
      <button onClick={logout}>Logout</button>
    </div>
  ) : (
    <button onClick={handleLogin}>Login</button>
  );
}

API Reference

AuthConfig

interface AuthConfig {
  login_url: string;
  refresh_url?: string;
  access_expiration_code?: number;
}

useAuth Hook

const {
  isAuthenticated,        // boolean - auth status
  login,             // (credentials) => Promise<LoginResponse>
  logout,            // () => void
  getLoginResponse,  // () => LoginResponse | null - retrieve login response data
  isLoading,         // boolean - request state
  error              // string | null - error message
} = useAuth<CustomResponseType>(); // Optional: specify custom response type

httpClient

A pre-configured Axios instance with automatic authentication:

import { httpClient, configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';

// All standard Axios methods are available
await httpClient.get('/api/users');
await httpClient.post('/api/users', userData);
await httpClient.put('/api/users/123', userData);
await httpClient.delete('/api/users/123');

// Automatically handles:
// - Adding Bearer token to requests
// - Token refresh on 401 errors
// - Retrying failed requests after refresh

Custom HTTP Client Configuration

Configure the httpClient with custom defaults like baseURL, headers, timeout, etc:

import { configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';

// Configure custom defaults for the httpClient
configureHttpClientDefaults({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'X-API-Version': 'v1'
  }
});

// Now all requests will use these defaults
await httpClient.get('/users'); // Actually requests: https://api.example.com/users
await httpClient.post('/users', userData); // Includes default headers + auth header

Generic Login Response

Support for custom API response structures:

// Default structure
interface DefaultLoginResponse {
  access_token: string;
  refresh_token?: string;
}

// Custom response type
interface CustomLoginResponse {
  access_token: string;
  refresh_token: string;
  user: { id: string; email: string };
  permissions: string[];
}

// Usage with custom type
const { login, getLoginResponse } = useAuth<CustomLoginResponse>();
const response = await login(credentials);
// response.user and response.permissions are now available

// Later, retrieve the stored login response
const storedResponse = getLoginResponse();
if (storedResponse) {
  console.log('User:', storedResponse.user);
  console.log('Permissions:', storedResponse.permissions);
}

Key Features

Automatic Token Refresh

Configure refresh_url and access_expiration_code for automatic token renewal when requests fail with the specified status code.

Authenticated Requests

The httpClient automatically adds Bearer tokens and handles token refresh:

import { httpClient, configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';

// All requests automatically include Authorization header
await httpClient.get('/api/users');
await httpClient.post('/api/users', userData);
await httpClient.put('/api/users/123', updatedData);

// You can also use with custom config per request
await httpClient.request({
  method: 'GET',
  url: '/api/users',
  headers: { 'Custom-Header': 'value' }
});

// Or configure defaults that apply to all requests
configureHttpClientDefaults({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

Persistent Authentication

Authentication state persists across browser sessions using localStorage.

Login Response Access

Use getLoginResponse() to retrieve the full login response data:

const { login, getLoginResponse } = useAuth<CustomLoginResponse>();

// After successful login
await login(credentials);

// Access the full login response data
const loginData = getLoginResponse();
if (loginData) {
  // Access any custom fields returned by your API
  console.log('User info:', loginData.user);
  console.log('Permissions:', loginData.permissions);
}

Note: Login response data is stored in memory only and will be null after browser refresh, while tokens are persisted in localStorage for maintaining authentication across sessions.

Requirements

  • React 16.8+
  • Modern browser with localStorage support

License

MIT