RegisterLogin
DocsPricing
RegisterLogin
  • Getting Started
  • Introduction
  • Quick Start
  • SDKs
  • React
  • TypeScript
  • Next.js
  • Express
  • NestJS
  • Python
  • API Reference
  • Support and Resources
  • FAQ
  • Contact Support

AuthSafe

Product

HighlightFeatureIntegrationPricingFAQ

Company

AboutBlogContactSitemap

Developer

DashboardDocumentation

Legal

Terms & ConditionsPrivacyComplianceShippingCancellation

© 2026 AuthSafe. All rights reserved.

We value your privacy

This website uses cookies for anonymous analytics to help us improve your experience. No personal information is stored or shared. You can allow or reject analytics tracking at any time. See our Privacy Policy.

We use cookies for anonymous analytics. No personal info is stored. See our Privacy Policy.

TypeScript SDK

Official AuthSafe SDK for TypeScript and JavaScript applications
v1.0.0
TypeScript
Browser
OAuth 2.1

Overview

The AuthSafe TypeScript SDK provides a robust, type-safe implementation of OAuth 2.1 and OpenID Connect authentication for browser-based applications. Built on top of oidc-client-ts, it handles all the complexity of modern authentication flows with built-in security features.

Key Features

  • 🔐 OAuth 2.1 & OIDC Compliant - Full implementation of modern authentication standards
  • 🛡️ PKCE Built-in - Automatic Proof Key for Code Exchange generation and validation
  • 🔄 Automatic Token Management - Silent refresh, automatic renewal, and cross-tab sync
  • 🎯 Type-Safe - Full TypeScript support with comprehensive type definitions
  • 🔑 MFA Support - TOTP, Email OTP, WebAuthn, and Backup Codes
  • 🌐 SSO Ready - Enterprise SSO integration support
  • 📦 Modular - Use only what you need with tree-shakeable exports

Installation

Install the package using npm:
npm install authsafe-ts
Or using yarn:
yarn add authsafe-ts
Or using pnpm:
pnpm add authsafe-ts

Quick Start

Here's the fastest way to get started with AuthSafe authentication:

1. Initialize the OAuth Service

import { OAuthService } from 'authsafe-ts';

const oauthService = new OAuthService({
  clientId: 'your-client-id',
  redirectUri: 'http://localhost:3000/callback',
  scope: ['openid', 'profile', 'email', 'offline_access'],
  env: 'production',
});

// Initialize on app startup to restore sessions
await oauthService.initialize();

2. Implement Login

// Redirect to login page
async function login() {
  await oauthService.signinRedirect();
}

// Or use a popup (no page navigation)
async function loginPopup() {
  const user = await oauthService.signinPopup();
  console.log('Logged in:', user);
}

3. Handle the Callback

// On your callback page (e.g., /callback)
async function handleCallback() {
  try {
    const user = await oauthService.signinRedirectCallback();
    console.log('Authentication successful:', user);

    // Redirect to your app
    window.location.href = '/dashboard';
  } catch (error) {
    console.error('Authentication failed:', error);
  }
}

4. Access User Information

async function getCurrentUser() {
  const user = await oauthService.getUser();

  if (user && !user.expired) {
    console.log('User:', user.profile);
    console.log('Access Token:', user.access_token);
  } else {
    console.log('Not authenticated');
  }
}

5. Implement Logout

async function logout() {
  await oauthService.signoutRedirect();
}

API Reference

Explore the complete API documentation:
OAuthService

Main service for OAuth 2.1 and OIDC flows. Handles authentication, token management, silent refresh, and session monitoring.

HttpService

HTTP client wrapper with automatic Bearer token injection, error handling, and request/response interceptors.

BrandingApi

Fetch branding configuration for OAuth clients (logo, colors, theme).

MfaApi

Manage multi-factor authentication methods (TOTP, Email OTP, WebAuthn, Backup Codes).

SSOApi

Query SSO provider configuration for enterprise single sign-on.

UserApi

Manage user profile information and account operations.

Type Definitions

Complete TypeScript type definitions for all APIs, requests, and responses.

Utilities

Helper functions including password strength calculation and validation utilities.


Security Features

The SDK implements multiple layers of security automatically:
Automatic Security
All security features are enabled by default. You don't need to configure PKCE, state management, or nonce handling - the SDK handles everything.

PKCE (Proof Key for Code Exchange)

  • Automatically generates code_verifier and code_challenge
  • Uses SHA-256 hashing for challenge generation
  • Validates code verifier during token exchange
  • Prevents authorization code interception attacks

State Management

  • CSRF protection with cryptographically secure random state
  • Automatic state validation on callback
  • Session storage for state persistence

Nonce Handling

  • Automatic nonce generation and inclusion in auth requests
  • Nonce validation against ID token claims
  • Prevents replay attacks and token substitution
  • Stored securely in sessionStorage

Token Storage

  • Secure sessionStorage for OIDC state and tokens
  • HTTP-only cookies for refresh tokens (cross-tab support)
  • Automatic token expiration handling
  • Silent token refresh before expiry

Examples

Vanilla JavaScript/TypeScript

import { OAuthService } from 'authsafe-ts';

class AuthManager {
  private oauthService: OAuthService;

  constructor() {
    this.oauthService = new OAuthService({
      clientId: 'your-client-id',
      redirectUri: window.location.origin + '/callback',
      scope: ['openid', 'profile', 'email', 'offline_access'],
      env: 'production',
    });

    this.oauthService.onStateChange(() => {
      this.updateUI();
    });
  }

  async init() {
    await this.oauthService.initialize();
    await this.updateUI();
  }

  async login() {
    await this.oauthService.signinRedirect();
  }

  async logout() {
    await this.oauthService.signoutRedirect();
  }

  async handleCallback() {
    await this.oauthService.signinRedirectCallback();
    window.location.href = '/';
  }

  async updateUI() {
    const user = await this.oauthService.getUser();
    const loginBtn = document.getElementById('login-btn');
    const logoutBtn = document.getElementById('logout-btn');
    const userInfo = document.getElementById('user-info');

    if (user && !user.expired) {
      loginBtn?.classList.add('hidden');
      logoutBtn?.classList.remove('hidden');
      if (userInfo) {
        userInfo.textContent = `Welcome, ${user.profile.name}!`;
      }
    } else {
      loginBtn?.classList.remove('hidden');
      logoutBtn?.classList.add('hidden');
      if (userInfo) {
        userInfo.textContent = '';
      }
    }
  }
}

// Initialize
const authManager = new AuthManager();
authManager.init();

With Vite

// main.ts
import { OAuthService } from 'authsafe-ts';

const oauthService = new OAuthService({
  clientId: import.meta.env.VITE_CLIENT_ID,
  redirectUri: import.meta.env.VITE_REDIRECT_URI,
  scope: ['openid', 'profile', 'email', 'offline_access'],
  env: import.meta.env.VITE_ENV,
});

// Check if this is a callback
if (window.location.pathname === '/callback') {
  oauthService
    .signinRedirectCallback()
    .then(() => {
      window.location.href = '/';
    })
    .catch(console.error);
} else {
  // Initialize and restore session
  oauthService.initialize();
}

export { oauthService };

Browser Support

  • Chrome/Edge: 90+
  • Firefox: 88+
  • Safari: 14+
  • Opera: 76+
Required Features:
  • Web Crypto API for PKCE
  • sessionStorage and cookies
  • ES2020+ JavaScript features

Next Steps

OAuthService Reference

Detailed documentation for the main OAuth service including all methods, events, and configuration options.

MFA Integration

Learn how to implement multi-factor authentication with TOTP, Email OTP, and WebAuthn.

API Reference

Explore the full AuthSafe API for advanced integrations.


Need Help?

Support
Having trouble? Check out our FAQ or contact support.