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 🙏

© 2026 – Pkg Stats / Ryan Hefner

authmate

v1.0.6

Published

It is SDK for AuthMate API that allows you to easily integrate AuthMate into your application. It provides a simple and intuitive interface for making API requests, handling authentication, and managing user sessions.

Readme

AuthMate SDK for TypeScript

npm version License: ISC

AuthMate SDK is a comprehensive TypeScript/JavaScript SDK that provides seamless authentication integration for your web applications. It offers easy-to-use APIs for user management, token handling, and protected route management with support for both React and Next.js applications.

🚀 Features

  • Complete Authentication Flow - Login, logout, registration, and user management
  • Token Management - Automatic token storage, refresh, and expiry handling
  • Protected Routes - Easy-to-implement route protection with multiple patterns
  • Universal Support - Works with React, Next.js, and vanilla JavaScript
  • TypeScript First - Full TypeScript support with type definitions
  • Flexible Storage - Configurable storage adapters (localStorage, cookies, etc.)
  • Automatic Redirects - Smart redirect handling for authentication flows

📦 Installation

npm install authmate
yarn add authmate
pnpm add authmate

🛠️ Quick Start

1. Basic Setup

import { tokenStorage, AuthMateClient } from 'authmate';

// Configure authentication redirection (one-time setup)
const setupAuth = (navigate: (path: string) => void) => {
  tokenStorage.configureRedirect({
    redirectTo: '/login',
    onUnauthenticated: (redirectTo) => {
      if (redirectTo) {
        navigate(redirectTo);
      }
    }
  });
};

// Initialize the AuthMate client
const authClient = new AuthMateClient({
  baseURL: 'https://your-authmate-api.com',
  // other configuration options
});

2. Authentication Methods

import { AuthMate } from 'authmate';

const authmate = new AuthMate({
  baseURL: 'https://your-authmate-api.com'
});

// Login
const loginUser = async () => {
  try {
    const response = await authmate.login({
      email: '[email protected]',
      password: 'password123'
    });
    console.log('Login successful:', response);
  } catch (error) {
    console.error('Login failed:', error);
  }
};

// Register
const registerUser = async () => {
  try {
    const response = await authmate.register({
      name: 'John Doe',
      email: '[email protected]',
      password: 'password123'
    });
    console.log('Registration successful:', response);
  } catch (error) {
    console.error('Registration failed:', error);
  }
};

// Logout
const logoutUser = async () => {
  try {
    await authmate.logout();
    console.log('Logout successful');
  } catch (error) {
    console.error('Logout failed:', error);
  }
};

🛡️ Protected Routes

Method 1: ProtectedRoute Component (Recommended)

import { ProtectedRoute, tokenStorage } from 'authmate';
import { BrowserRouter as Router, Routes, Route, useNavigate } from 'react-router-dom';

function App() {
  const navigate = useNavigate();

  useEffect(() => {
    // One-time configuration
    tokenStorage.configureRedirect({
      redirectTo: '/login',
      onUnauthenticated: (redirectTo) => navigate(redirectTo)
    });
  }, [navigate]);

  return (
    <Router>
      <Routes>
        {/* Public Routes */}
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />

        {/* Protected Routes - Wrap multiple routes */}
        <Route path="/*" element={
          <ProtectedRoute fallback={<div>Redirecting...</div>}>
            <Routes>
              <Route path="/dashboard" element={<Dashboard />} />
              <Route path="/profile" element={<Profile />} />
              <Route path="/settings" element={<Settings />} />
              <Route path="/admin" element={<Admin />} />
            </Routes>
          </ProtectedRoute>
        } />
      </Routes>
    </Router>
  );
}

Method 2: useAuth Hook

import { useAuth } from 'authmate';

function ProtectedPage() {
  const { isAuthenticated, checkAuthentication, clearTokens } = useAuth();

  useEffect(() => {
    checkAuthentication();
  }, []);

  if (!isAuthenticated) {
    return <div>Redirecting to login...</div>;
  }

  const handleLogout = () => {
    clearTokens();
  };

  return (
    <div>
      <h1>Protected Content</h1>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}

Method 3: requireAuth Function

import { requireAuth } from 'authmate';

function ProtectedComponent() {
  useEffect(() => {
    // Check auth with token expiry validation
    const isAuthenticated = requireAuth(true);
    if (!isAuthenticated) {
      // User will be redirected automatically
      return;
    }
  }, []);

  return <div>Protected Content</div>;
}

🌐 Next.js Integration

App Router (app/layout.tsx)

'use client';
import { tokenStorage } from 'authmate';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();

  useEffect(() => {
    if (typeof window !== 'undefined') {
      tokenStorage.configureRedirect({
        redirectTo: '/login',
        onUnauthenticated: (redirectTo) => {
          if (redirectTo) {
            router.push(redirectTo);
          }
        }
      });
    }
  }, [router]);

  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Protected Page Example

'use client';
import { requireAuth } from 'authmate';
import { useEffect } from 'react';

export default function Dashboard() {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      requireAuth(true);
    }
  }, []);

  return (
    <div>
      <h1>Dashboard</h1>
      <p>This is a protected page</p>
    </div>
  );
}

🔧 API Reference

AuthMate Class

import { AuthMate } from 'authmate';

const authmate = new AuthMate({
  baseURL: string;           // Your AuthMate API base URL
  timeout?: number;          // Request timeout (default: 10000ms)
  retries?: number;          // Number of retries (default: 3)
});

Methods

  • login(credentials) - Authenticate user and store tokens
  • register(userData) - Register new user
  • logout() - Logout user and clear tokens
  • getProfile() - Get current user profile
  • updateProfile(data) - Update user profile
  • changePassword(data) - Change user password
  • refreshToken() - Refresh access token
  • verifyEmail(token) - Verify email address
  • resetPassword(email) - Request password reset
  • confirmPasswordReset(data) - Confirm password reset

tokenStorage

import { tokenStorage } from 'authmate';

// Configuration
tokenStorage.configureRedirect({
  redirectTo: '/login',
  onUnauthenticated: (redirectTo) => { /* handle redirect */ }
});

// Token management
tokenStorage.set(accessToken, refreshToken);
tokenStorage.getAccess();
tokenStorage.getRefresh();
tokenStorage.clear();
tokenStorage.isAuthenticated();

// Authentication checking with redirect
tokenStorage.checkAuthAndRedirect();
tokenStorage.checkTokenExpiryAndRedirect();

useAuth Hook

import { useAuth } from 'authmate';

const {
  isAuthenticated,          // Current auth status
  checkAuthentication,      // Function to check and redirect
  clearTokens,             // Clear stored tokens
  getAccessToken,          // Get current access token
  getRefreshToken,         // Get current refresh token
  setTokens               // Set new tokens
} = useAuth({
  checkTokenExpiry?: boolean;     // Check token expiration (default: true)
  redirectOnFailure?: boolean;    // Auto-redirect on failure (default: true)
});

ProtectedRoute Component

import { ProtectedRoute } from 'authmate';

<ProtectedRoute 
  fallback={<LoadingSpinner />}    // Component to show while redirecting
  checkTokenExpiry={true}          // Check token expiration (default: true)
>
  {/* Your protected content */}
</ProtectedRoute>

🔧 Advanced Configuration

Custom Storage Adapter

import { tokenStorage, type StorageAdapter } from 'authmate';

// Custom cookie storage
const cookieStorage: StorageAdapter = {
  getItem: (key: string) => getCookie(key) || null,
  setItem: (key: string, value: string) => setCookie(key, value),
  removeItem: (key: string) => deleteCookie(key)
};

// Use custom storage
tokenStorage.configure(cookieStorage);

Error Handling

import { AuthMate, AuthMateError } from 'authmate';

try {
  await authmate.login(credentials);
} catch (error) {
  if (error instanceof AuthMateError) {
    console.error('Auth error:', error.message);
    console.error('Status code:', error.statusCode);
  } else {
    console.error('Unexpected error:', error);
  }
}

📚 Examples

Check out the PROTECTED_ROUTES_USAGE.md file for more detailed examples and usage patterns.

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get started.

📄 License

This project is licensed under the ISC License - see the LICENSE file for details.

🆘 Support

🔄 Changelog

v1.0.1

  • Added protected route components and hooks
  • Improved token management with automatic refresh
  • Added Next.js support
  • Enhanced TypeScript definitions

v1.0.0

  • Initial release with core authentication features