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

sdk-simple-auth

v2.1.1

Published

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

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: '[email protected]',
  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: '[email protected]',
        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": "[email protected]", "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: '[email protected]',
  password: 'password',
  device_name: 'my-web-app'
});

// Compatible with Sanctum responses:
// {
//   "user": { "id": 1, "email": "[email protected]", "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