Getting Started with the SDK
The AuthOS SDK (@drmhse/sso-sdk) is a zero-dependency, strongly-typed TypeScript client library that makes it easy to integrate AuthOS into any JavaScript or TypeScript application.
Features
- Zero Dependencies: Built on native
fetchAPI - no external dependencies - Framework Agnostic: Pure TypeScript - works in any JavaScript environment
- Strongly Typed: Complete TypeScript definitions for all API endpoints
- Automatic Session Management: Invisible token persistence and auto-refresh
- Environment Agnostic Storage: Auto-detects localStorage (browser) or memory (Node.js)
- Predictable Error Handling: Custom
SsoApiErrorclass with structured error information - Modern: Supports Node.js 18+ and all modern browsers
Installation
Install the SDK using npm:
npm install @drmhse/sso-sdk
Initialization
Before you can authenticate users, you need to create an instance of the SDK client. At this stage, you don’t need a token yet:
import { SsoClient } from '@drmhse/sso-sdk';
const sso = new SsoClient({
baseURL: 'https://sso.example.com' // Your AuthOS API URL
});
The client is now ready to perform authentication operations.
Your First Authentication
This section shows you how to authenticate a user with email and password. The SDK automatically handles session management, token persistence, and auto-refresh. Here’s a complete, copy-pasteable example:
import { SsoClient, SsoApiError } from '@drmhse/sso-sdk';
const sso = new SsoClient({
baseURL: 'https://sso.example.com'
});
async function login() {
try {
// Login with email and password
// The SDK automatically handles token storage and configuration
await sso.auth.login({
email: 'user@example.com',
password: 'SecurePass123!'
});
// You can now make authenticated requests - tokens are auto-injected
const profile = await sso.user.getProfile();
console.log(`Successfully logged in as: ${profile.email}`);
// Check authentication status
console.log('Is authenticated:', sso.isAuthenticated());
} catch (error) {
if (error instanceof SsoApiError) {
if (error.isAuthError()) {
console.error('Invalid email or password');
} else {
console.error(`API Error: ${error.message}`);
}
}
}
}
That’s it! After running this code successfully, you’ll have:
- An authenticated SDK client ready to make API calls
- Access and refresh tokens automatically stored in localStorage
- Automatic token injection on all subsequent requests
- Automatic token refresh when tokens expire (no 401 errors)
Making Authenticated Requests
On subsequent page loads or app restarts, the SDK automatically restores the user’s session from localStorage:
import { SsoClient, SsoApiError } from '@drmhse/sso-sdk';
// Initialize the client - it automatically loads tokens from localStorage
const sso = new SsoClient({
baseURL: 'https://sso.example.com'
});
// Now you can make authenticated API calls
async function loadUserData() {
try {
// Check if user is authenticated
if (!sso.isAuthenticated()) {
console.log('User not logged in');
// Redirect to login page
return;
}
const profile = await sso.user.getProfile();
console.log(`Welcome back, ${profile.email}`);
const orgs = await sso.organizations.list();
console.log(`You belong to ${orgs.length} organization(s)`);
} catch (error) {
if (error instanceof SsoApiError) {
console.error(`API Error: ${error.message}`);
}
}
}
// Optional: React to authentication state changes
sso.onAuthStateChange((isAuthenticated) => {
if (isAuthenticated) {
console.log('User logged in');
} else {
console.log('User logged out or session expired');
// Redirect to login page
}
});
Handling Token Expiration
Good news: Token expiration is handled automatically! The SDK automatically refreshes expired access tokens using the refresh token. You don’t need to write any manual token refresh logic.
// When you make an API call with an expired token:
async function fetchData() {
try {
// The SDK automatically:
// 1. Detects the 401 error from the expired token
// 2. Uses the refresh token to get a new access token
// 3. Retries the original request with the new token
// 4. Returns the result - you never see the 401 error!
const profile = await sso.user.getProfile();
console.log('Success:', profile);
} catch (error) {
// You'll only see errors if refresh fails (e.g., refresh token expired)
if (error instanceof SsoApiError) {
console.error('Session expired - please log in again');
// Redirect user to login page
}
}
}
Advanced: Manual Token Refresh
If you need to manually refresh tokens (e.g., before a critical operation), you can still do so:
async function manualRefresh() {
try {
const currentToken = await sso.getToken();
if (currentToken) {
// Manually trigger a refresh
const tokens = await sso.auth.refreshToken(currentToken);
console.log('Token refreshed successfully');
}
} catch (error) {
console.error('Manual refresh failed:', error);
}
}
For more details on authentication flows, see the Authentication Flows guide.
Handling Logout
When a user logs out, the SDK automatically clears the session and removes tokens from storage:
async function logout() {
try {
// The SDK automatically:
// 1. Calls the logout endpoint to invalidate the token on the server
// 2. Clears the session from the SDK client
// 3. Removes tokens from localStorage
await sso.auth.logout();
console.log('Logged out successfully');
// Redirect to login page or public home page
window.location.href = '/login';
} catch (error) {
// Even if the server request fails, the session is automatically cleared
if (error instanceof SsoApiError) {
console.error(`Logout error: ${error.message}`);
}
}
}
What Happens During Logout:
- Server-side token revocation (if network request succeeds)
- Automatic session clearing (always happens, even if network fails)
- Automatic token removal from localStorage
- Authentication state change notification (if you’re using
onAuthStateChange)
Error Handling
The SDK throws SsoApiError for API errors:
try {
await sso.user.getProfile();
} catch (error) {
if (error instanceof SsoApiError) {
console.error(`Status: ${error.status}`);
console.error(`Message: ${error.message}`);
console.error(`Error Code: ${error.errorCode}`);
// Check error type
if (error.isAuthError()) {
// Handle authentication errors (401, 403)
} else if (error.isNotFoundError()) {
// Handle not found (404)
}
}
}
Next Steps
Explore the guides and reference documentation to learn more:
Integration Guides
- Authentication Flows - OAuth, Admin, and Device flows
- Password Authentication - Registration, login, and password reset
- MFA Management - Multi-factor authentication
SDK Reference
- Auth Module - Authentication methods
- User Module - User profile and MFA
- Organizations Module - Organization management
- All Modules - Complete SDK reference