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

andydefer-jwt

v2.4.1

Published

A JWT authentication package for React and Inertia.js using Zustand.

Readme

andydefer-jwt

Une solution de gestion d’authentification JWT pour React avec Zustand et Inertia.js, incluant :

  • Login / Logout / Register
  • Gestion du token JWT et clé publique
  • Initialisation automatique à partir de la session
  • Vérification de signature
  • Stockage persistant côté client (localStorage)
  • Configuration dynamique de l’API et des routes

⚠️ Ce package est conçu pour fonctionner en tandem avec le package Laravel andydefer/jwt, qui fournit l’API JWT côté serveur.


🚀 Installation

npm install andydefer-jwt

ou

yarn add andydefer-jwt

⚙️ Usage

1️⃣ Hook principal useAuth

import { useAuth } from 'andydefer-jwt';

const MyComponent = () => {
  const { user, isAuthenticated, login, logout, register, isLoading, error } = useAuth();

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <p>Bienvenue, {user?.name}</p>
          <button onClick={logout}>Se déconnecter</button>
        </div>
      ) : (
        <div>
          <button onClick={() => login('[email protected]', 'password')}>Se connecter</button>
        </div>
      )}
      {isLoading && <p>Chargement...</p>}
      {error && <p style={{ color: 'red' }}>{error}</p>}
    </div>
  );
};

2️⃣ Store useAuthStore

Pour accéder directement aux fonctionnalités avancées ou créer des hooks personnalisés :

import { useAuthStore } from 'andydefer-jwt';

// Configurer le store avec une API personnalisée et routes
import { createAuthStore } from 'andydefer-jwt';
const customAuthStore = createAuthStore({
  baseURL: 'https://api.example.com',
  routes: {
    login: '/auth/login',
    register: '/auth/register',
    logout: '/auth/logout',
    fetchUser: '/auth/me',
    refreshToken: '/auth/refresh',
  },
});

const token = customAuthStore(state => state.token);
const login = customAuthStore(state => state.login);

login('[email protected]', 'password');

📝 API

useAuth()

| Nom | Type | Description | | -------------------------------------------- | --------------------- | ------------------------------------- | | isAuthenticated | boolean | Indique si l’utilisateur est connecté | | user | User \| null | Objet utilisateur courant | | isLoading | boolean | Indique que l’action est en cours | | error | string \| null | Message d’erreur si échec | | login(email, password, deviceId?) | () => Promise<void> | Connecte un utilisateur | | logout() | () => Promise<void> | Déconnecte l’utilisateur | | register(name, email, password, deviceId?) | () => Promise<void> | Enregistre un nouvel utilisateur |

useAuthStore()

| Nom | Type | Description | | -------------------------------------------- | --------------------- | ------------------------------------- | | token | string \| null | Token JWT actuel | | user | User \| null | Utilisateur courant | | isLoading | boolean | Indicateur de chargement | | error | string \| null | Message d’erreur | | isInitialized | boolean | Indique si le store a été initialisé | | initialize() | () => Promise<void> | Initialise le store depuis la session | | login(email, password, deviceId?) | () => Promise<void> | Connexion | | register(name, email, password, deviceId?) | () => Promise<void> | Inscription | | logout() | () => void | Déconnexion | | fetchUser() | () => Promise<void> | Récupère l’utilisateur depuis l’API | | refreshToken() | () => Promise<void> | Rafraîchit le token JWT | | config | AuthConfig | Contient baseURL et routes |


🔧 Configuration dynamique (authConfig.ts)

Exemple de configuration personnalisée :

export const myAuthConfig = {
  baseURL: 'https://api.example.com',
  routes: {
    login: '/auth/login',
    register: '/auth/register',
    logout: '/auth/logout',
    fetchUser: '/auth/me',
    refreshToken: '/auth/refresh',
  },
};

Puis créer le store avec cette config :

import { createAuthStore } from 'andydefer-jwt';
import { myAuthConfig } from './authConfig';

export const useAuthStore = createAuthStore(myAuthConfig);

🔒 Stockage persistant

Le token et l’utilisateur sont stockés via Zustand Persist dans localStorage sous le nom :

jwt-auth-storage

🧩 Intégration backend Laravel

composer require andydefer/jwt
php artisan migrate
php artisan vendor:publish --provider="AndyDefer\Jwt\JwtAuthServiceProvider" --tag="routes"

🛠 Workflow complet avec Makefile

make install
make test
make build
make version-minor
make publish
make release-interactive

🧪 Tests

npm test

💡 Bonnes pratiques

  • Vérifier isAuthenticated avant de rendre des contenus protégés.
  • Utiliser error pour afficher les messages d’erreur.
  • Ne jamais exposer directement le token.
  • Synchroniser le front-end avec le backend Laravel.