JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 50
  • Score
    100M100P100Q63280F
  • License MIT

Universal JavaScript/TypeScript authentication SDK with multi-backend support, automatic token refresh, and React integration

Package Exports

  • sdk-simple-auth

Readme

๐Ÿ” SDK Simple Auth

Universal JavaScript/TypeScript authentication library with multi-backend support

NPM Version License TypeScript

๐Ÿš€ Key Features

  • โœ… Multi-Backend: Compatible with Node.js/Express, Laravel Sanctum, standard JWT
  • โœ… TypeScript: Full type support and native compatibility
  • โœ… React Ready: Hooks and components ready to use
  • โœ… Auto-detection: Automatically detects backend type
  • โœ… Data Preservation: Maintains all original backend data
  • โœ… Auto Refresh: Intelligent token management
  • โœ… Flexible Storage: LocalStorage, IndexedDB, memory
  • โœ… Zero Dependencies: No heavy external dependencies

๐Ÿ“ฆ Installation

npm install sdk-simple-auth

๐ŸŽฏ Quick Start

Basic Configuration

import { AuthSDK } from 'sdk-simple-auth';

const auth = new AuthSDK({
  authServiceUrl: 'http://localhost:3000'
});

// Login
const user = await auth.login({
  email: 'user@example.com',
  password: 'my-password'
});

console.log('Authenticated user:', user);

With React

import React, { useEffect, useState } from 'react';
import { AuthSDK } from 'sdk-simple-auth';

function App() {
  const [auth] = useState(() => new AuthSDK({
    authServiceUrl: process.env.REACT_APP_API_URL
  }));
  const [user, setUser] = useState(null);

  useEffect(() => {
    // Check existing session
    auth.isAuthenticated().then(isAuth => {
      if (isAuth) {
        setUser(auth.getCurrentUser());
      }
    });

    // Listen to auth changes
    const unsubscribe = auth.onAuthStateChanged((state) => {
      setUser(state.user);
    });

    return unsubscribe;
  }, [auth]);

  const handleLogin = async () => {
    try {
      const user = await auth.login({
        email: 'user@example.com',
        password: 'password'
      });
      console.log('Login successful:', user);
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <div>
      {user ? (
        <div>
          <h1>Hello, {user.name}!</h1>
          <button onClick={() => auth.logout()}>
            Logout
          </button>
        </div>
      ) : (
        <button onClick={handleLogin}>
          Login
        </button>
      )}
    </div>
  );
}

๐Ÿ› ๏ธ Backend Configuration

Node.js/Express

import { createQuickNodeAuth } from 'sdk-simple-auth';

const auth = createQuickNodeAuth('http://localhost:3000');

// Your backend should return:
// {
//   "success": true,
//   "data": {
//     "user": { "id": 1, "email": "user@test.com", "name": "User" },
//     "token": "jwt-token-here",
//     "refreshToken": "refresh-token-here"
//   }
// }

Laravel Sanctum

import { createQuickSanctumAuth } from 'sdk-simple-auth';

const auth = createQuickSanctumAuth('http://localhost:8000/api');

const user = await auth.login({
  email: 'user@example.com',
  password: 'password',
  device_name: 'my-web-app'
});

// Compatible with Sanctum responses:
// {
//   "user": { "id": 1, "email": "user@test.com", "created_at": "..." },
//   "token": "1|sanctum-token-here"
// }

Standard JWT

import { AuthSDK } from 'sdk-simple-auth';

const auth = new AuthSDK({
  authServiceUrl: 'http://localhost:3000',
  backend: {
    type: 'jwt-standard',
    userSearchPaths: ['user', 'data.user'],
    fieldMappings: {
      userId: ['sub', 'id'],
      email: ['email'],
      name: ['name', 'username']
    }
  }
});

๐Ÿ”ง Core API

Authentication Methods

// Login
const user = await auth.login(credentials);

// Register
const user = await auth.register(userData);

// Logout
await auth.logout();

// Check authentication
const isAuth = await auth.isAuthenticated();

// Get current user
const user = auth.getCurrentUser();

// Get valid token (with auto refresh)
const token = await auth.getValidAccessToken();

// Authorization headers
const headers = await auth.getAuthHeaders();
// { Authorization: 'Bearer jwt-token' }

Token Management

// Manual refresh
const newTokens = await auth.refreshTokens();

// Force refresh
const tokens = await auth.forceRefreshTokens();

// Session information
const sessionInfo = await auth.getExtendedSessionInfo();
console.log({
  isValid: sessionInfo.isValid,
  expiresIn: sessionInfo.expiresIn,
  canRefresh: sessionInfo.canRefresh
});

Events and State

// Listen to state changes
const unsubscribe = auth.onAuthStateChanged((state) => {
  console.log('State:', state.isAuthenticated);
  console.log('User:', state.user);
  console.log('Loading:', state.loading);
  console.log('Error:', state.error);
});

// Get current state
const state = auth.getState();

๐Ÿ—๏ธ Advanced Configuration

Complete Configuration

const auth = new AuthSDK({
  authServiceUrl: 'http://localhost:3000',
  
  // Custom endpoints
  endpoints: {
    login: '/auth/login',
    register: '/auth/register',
    refresh: '/auth/refresh',
    logout: '/auth/logout',
    profile: '/auth/profile'
  },
  
  // Storage configuration
  storage: {
    type: 'localStorage', // 'localStorage' | 'indexedDB'
    tokenKey: 'access_token',
    refreshTokenKey: 'refresh_token',
    userKey: 'user_data'
  },
  
  // Auto refresh
  tokenRefresh: {
    enabled: true,
    bufferTime: 300, // Refresh 5 min before expiry
    maxRetries: 3
  },
  
  // Backend configuration
  backend: {
    type: 'node-express',
    userSearchPaths: ['user', 'data.user'],
    fieldMappings: {
      userId: ['id', 'user_id'],
      email: ['email'],
      name: ['name', 'full_name']
    },
    preserveOriginalData: true
  }
});

๐Ÿงช Testing and Debugging

Debug Mode

// Analyze your API response
auth.debugResponse(response);

// Debug current token
auth.debugToken();

// Debug complete session
auth.debugSession();

// Test data extraction
auth.testExtraction(mockResponse);

Backend Auto-detection

import { quickAnalyzeAndCreate } from 'sdk-simple-auth';

// Automatically analyzes response and creates SDK
const auth = quickAnalyzeAndCreate(
  responseFromYourAPI,
  'http://localhost:3000'
);

๐Ÿ”’ Error Handling

try {
  const user = await auth.login(credentials);
} catch (error) {
  if (error.message.includes('credentials')) {
    console.log('Invalid credentials');
  } else if (error.message.includes('network')) {
    console.log('Network error');
  } else {
    console.log('Unknown error:', error.message);
  }
}

// Listen to global errors
auth.onAuthStateChanged((state) => {
  if (state.error) {
    console.error('Authentication error:', state.error);
  }
});

๐Ÿ“ฑ Compatibility

  • โœ… Browsers: Chrome, Firefox, Safari, Edge (ES2018+)
  • โœ… Node.js: 14.x, 16.x, 18.x, 20.x
  • โœ… Frameworks: React, Vue, Angular, Vanilla JS
  • โœ… Bundlers: Webpack, Vite, Rollup, Parcel
  • โœ… TypeScript: 4.5+

๐Ÿ“š Documentation

๐Ÿค Contributing

  1. Fork the repository
  2. Create a branch: git checkout -b feature/new-feature
  3. Commit: git commit -am 'Add new feature'
  4. Push: git push origin feature/new-feature
  5. Create Pull Request

๐Ÿ“„ License

MIT License - see LICENSE for details.

๐Ÿ†˜ Support


Developed by olivio-git