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

@bisham/react-jwt-auth

v0.3.1

Published

React Jwt Auth is an auth state management library that handles all the core functionality of jwt auth including de-duping, attaching auth token in each request

Readme

Overview

@bisham/react-jwt-auth simplifies JWT authentication flow in your React apps by managing access tokens, including automatic handling of token expiration, refreshing tokens, and deduplication of token fetch requests.

Features

  • JWT Token Validation: Ensures that the JWT token format is correct and checks the expiration (exp) field if it exist.
  • Token Expiration Handling: Automatically detects when the token has expired and triggers a refresh when exp is in jwt payload.
  • Automatic Token Refresh: Supports automatic fetching of new access tokens and handles deduplication of token requests.
  • Secure Authorization Context: Provides a context for managing the user's authentication state across your app.
  • Seamless Integration with Axios: Automatically attaches the Authorization header with the correct access token in your axios requests.
  • Flexible Debugging: Enables detailed debug logging to help you track the authentication flow.

Installation

To install the package, run the following command:

npm install @bisham/react-jwt-auth

or

yarn add @bisham/react-jwt-auth

Usage

Setting Up the AuthProvider

Wrap your application with the AuthProvider component to manage authentication state across your app.

import React from "react";
import { AuthProvider } from "@bisham/react-jwt-auth";
import axios from "axios";

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

const getAccessToken = async () => {
  // Implement your token fetching logic (e.g., from localStorage or a refresh API)
};

const App = () => {
  return (
    <AuthProvider
      axiosInstance={axiosPrivate}
      defaultValue={{ accessToken: localStorage.getItem("accessToken") }}
      getAccessToken={getAccessToken}
      debug
      onSignOut={() => console.log("Signed out")}
      onSignIn={(accessToken)=>{
        // something to do when user signs in into the app
        // using signIn callback provided by `useAuth`
      }}
    >
      {/* Your app components */}
    </AuthProvider>
  );
};

export default App;

Accessing Authentication State

You can access the authentication state anywhere in your app using the useAuth hook:

import { useAuth } from "@bisham/react-jwt-auth";

const MyComponent = () => {
  const { isAuthenticated, signOut } = useAuth();

  const fetchData = async () => {
    try {
      // Authentication is Handled by AuthProvider Wrapper
      const response = await axiosPrivate.get("/protected-data", {});
      console.log(response.data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <button onClick={fetchData}>Fetch Protected Data</button>
          <button onClick={signOut}>Sign Out</button>
        </div>
      ) : (
        <p>You are not authenticated</p>
      )}
    </div>
  );
};

Handling Token Expiration

This package checks that the JWT token includes the exp (expiration) field in the payload. If the token is expired, the package will automatically try to refresh the token by calling the getNewTokens function you provide. If exp field is missing then it will check if server is sending 401 error then retry to getNewTokens method.

API

AuthProvider

  • Props:
    • axiosInstance (required): An instance of Axios that will be used for authenticated requests.
    • defaultValue (optional): An object containing the initial accessToken.
    • getAccessToken (required): A function that fetches the access token.
    • debug (optional): Boolean flag to enable or disable debug logging (default: false).
    • onSignOut (optional): A callback function that is triggered when the user signs out.

useAuth

  • Returns: An object containing the following methods and properties:
    • isAuthenticated: Boolean indicating whether the user is authenticated.
    • signIn(accessToken): Function to sign the user in with the provided accessToken.
    • signOut(): Function to sign the user out.
    • getAccessToken(): Function to get the current access token (or fetch a new one if expired).
    • onSignIn: Function callback that is triggered when user signs in via signin function provided by useAuth.

Important Notes

  • Make sure your token fetching logic in getAccessToken is set up properly to handle token expiration and refreshing.
  • If you encounter issues or need debugging, enable the debug flag when using AuthProvider to get detailed logs.

License

This package is licensed under the MIT License.


For any questions or feature requests, feel free to open an issue on the GitHub repository.