Skip to content

Repository files navigation

auth-client SDK

A lightweight, framework-agnostic authentication client SDK designed for scalable React (and non-React) apps using centralized login via Keycloak + Auth Service.


📦 Installation

npm install @spidy092/auth-client

Note: This package supports both ES Modules (import) and CommonJS (require).

CommonJS Usage:

const { auth } = require('auth-client');
const api = require('auth-client/api').default; // Note: .default is required for api
const { decodeToken } = require('auth-client/utils/jwt');

🔧 Setup

import { auth } from 'auth-client';

auth.setConfig({
  clientKey: 'admin-ui',
  authBaseUrl: 'http://auth.localhost:4000/auth',
});

🚀 Usage

Login

auth.login();

For applications that coordinate login across same-origin tabs, prefer the promise-based entry point. It uses the Web Locks API when available and falls back to the storage lease for older or restricted browsers:

await auth.loginAsync();

The login lease expires after 5 minutes as a crash-recovery upper bound. It is not a user-facing wait: a waiting tab should offer an immediate takeover action that calls auth.clearLoginLease() before starting a new login.

Handle Callback

auth.handleCallback(); // Call this on /callback page

Logout

auth.logout();

Cross-tab auth events

const unsubscribe = auth.subscribeToAuthEvents((event) => {
  if (event.type === 'LOGIN_COMPLETED') {
    // Re-establish this tab's session with auth.restoreSession().
  }
});

// Call when the component or application is disposed.
unsubscribe();

Login start/completion and logout events use the configured logoutChannelName and carry metadata only. Applications must restore their own session; tokens are never sent through the cross-tab transport.

Get Token

const token = auth.getToken();

🧠 React Integration

Provider

import { AuthProvider } from 'auth-client/react/AuthProvider';

<AuthProvider>
  <App />
</AuthProvider>

Hook

import { useAuth } from 'auth-client/react/useAuth';

const { user, token, login, logout } = useAuth();

📡 Authenticated API

import api from 'auth-client/api';

api.get('/me'); // sends Authorization header

🧪 Utilities

import { decodeToken, isTokenExpired } from 'auth-client/utils/jwt';

✅ Built-in Features

  • Token handling (in-memory + localStorage)
  • CSRF-safe login with state param
  • Auto API auth header via Axios
  • React support via context and hooks

🔐 Security

  • No HttpOnly cookies — safe from XSS if you sandbox localStorage
  • Handles CSRF via state
  • Designed for refresh via backend /refresh

📦 To Publish Locally

npm pack
npm install ../auth-client-1.0.0.tgz

🏁 License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages