Skip to main content

NAuthClientConfig

Package: @nauth-toolkit/client Type: Interface

Configuration options for initializing NAuthClient.

import { NAuthClientConfig } from '@nauth-toolkit/client';

Properties

PropertyTypeRequiredDescription
baseUrlstringYesBackend auth API base URL (e.g., https://api.example.com/auth)
authPathPrefixstringNoPath prefix prepended to all endpoint paths (e.g., /auth). Useful when your auth routes share a common prefix.
tokenDeliveryTokenDeliveryModeYesToken delivery mode. Choose based on platform (web or mobile).
onAuthResponse(response: [AuthResponse](./types/auth-response), context: [AuthResponseContext](#authresponsecontext)) => void | Promise<void>NoCustom handler for auth responses. Overrides automatic navigation. Use for dialog-based flows. See AuthResponseContext for context properties.
navigationHandler(url: string) => void | Promise<void>NoCustom navigation function. If not provided, uses window.location.replace (guards) or window.location.href
redirectsNAuthRedirectsConfigNoRedirect URLs and challenge routing configuration (see below)
recaptcha{ enabled: boolean; version: 'v2' | 'v3' | 'enterprise'; siteKey: string; action?: string; autoLoadScript?: boolean; language?: string }NoreCAPTCHA configuration for bot protection. See reCAPTCHA Guide.
storageNAuthStorageAdapterNoCustom storage adapter. Defaults to localStorage (browser) or in-memory.
csrf{ cookieName?: string; headerName?: string }NoCSRF configuration for cookie mode. Defaults: nauth_csrf_token, x-csrf-token
endpointsPartial<[NAuthEndpoints](./types/nauth-endpoints)>NoOverride default endpoint paths. See NAuthEndpoints for all available endpoints.
deviceTrust{ headerName?: string; storageKey?: string }NoDevice trust header and storage configuration
headersRecord<string, string>NoAdditional headers to include in all requests
timeoutnumberNoRequest timeout in milliseconds. Default: 30000 (30 seconds)
onSessionExpired() => voidNo(Deprecated) Use redirects.sessionExpired instead
onTokenRefresh() => voidNoCallback after successful token refresh
onAuthStateChange(user: [AuthUser](./types/auth-user) | null) => voidNoCallback when authentication state changes
onError(error: [NAuthClientError](./nauth-client-error)) => voidNoGlobal error handler
httpAdapterHttpAdapterNoHTTP adapter for making requests. Auto-provided in Angular (NAuthModule). In React/Vue, uses the built-in FetchAdapter by default.
debugbooleanNoEnable debug logging
admin{ pathPrefix?: string; endpoints?: Partial<[NAuthAdminEndpoints](./types/nauth-admin-endpoints)>; headers?: Record<string, string> }NoAdmin operations configuration. When provided, enables client.admin.* methods. See AdminOperations for details.

Redirect URLs

The redirects property accepts a NAuthRedirectsConfig object that provides platform-agnostic routing configuration for all authentication flows (login, signup, social OAuth, and challenges).

See NAuthRedirectsConfig for complete interface documentation.

PropertyTypeRequiredDefaultDescription
successstringNo'/'URL to redirect after successful authentication (login, signup, OAuth)
sessionExpiredstringNo'/login'URL to redirect when session expires (refresh fails with 401)
oauthErrorstringNo'/login'URL to redirect when OAuth authentication fails
challengeBasestringNo'/auth/challenge'Base URL for challenge routes. Challenge type appended by default
challengeRoutesPartial<Record<[AuthChallenge](./types/auth-challenge), string>>NoundefinedCustom route mapping for each challenge type. Overrides default route construction. See AuthChallenge enum for all challenge types.
useSingleChallengeRoutebooleanNofalseWhen true, uses query param mode: /auth/challenge?challenge=VERIFY_EMAIL. When false, uses separate routes: /auth/challenge/verify-email
mfaRoutesMfaRoutesConfigNoundefinedMFA-specific route overrides (only applies to MFA_REQUIRED challenge). See MFA Routes Configuration below.

MFA Routes Configuration

Fine-grained control over MFA navigation. Only applies when challenge type is MFA_REQUIRED. The SDK selects routes based on the MFA method and available options:

PropertyTypeRequiredDescription
passkeystringNoRoute for passkey verification. Used when preferredMethod is 'passkey'
selectorstringNoRoute for MFA method selector. Used when multiple availableMethods exist and no preferredMethod is set
defaultstringNoRoute for other MFA methods. Used for SMS, email, and TOTP (MFAMethod values: 'sms', 'email', 'totp')

Route Building Priority:

The SDK builds challenge URLs in this order (highest to lowest priority):

  1. challengeRoutes - Custom route mapping (overrides everything)
  2. useSingleChallengeRoute - Query param mode (/auth/challenge?challenge=VERIFY_EMAIL)
  3. mfaRoutes - MFA-specific routes (only for MFA_REQUIRED challenge)
  4. Default separate routes - Kebab-case routes based on challenge type

Example:

import { AuthChallenge } from '@nauth-toolkit/client';

{
redirects: {
loginSuccess: '/dashboard',
signupSuccess: '/onboarding',
sessionExpired: '/login?expired=true',
oauthError: '/login?error=oauth',
challengeBase: '/auth/challenge',

// Custom routes for specific challenges
challengeRoutes: {
[AuthChallenge.VERIFY_EMAIL]: '/verify-email',
[AuthChallenge.MFA_REQUIRED]: '/auth/two-factor',
},

// MFA-specific routes (only for MFA_REQUIRED)
mfaRoutes: {
passkey: '/auth/passkey',
selector: '/auth/choose-method',
default: '/auth/verify-code',
},

// Use query param mode instead of separate routes
useSingleChallengeRoute: false,
},
}

Related Types:

The SDK supports multiple navigation patterns for handling challenges. Choose based on your app's routing structure:

Pattern 1: Separate Routes (Default)

Each challenge gets its own route. Uses challengeBase with kebab-case challenge names.

{
redirects: {
challengeBase: '/auth/challenge';
}
}
// Results:
// - /auth/challenge/verify-email
// - /auth/challenge/verify-phone
// - /auth/challenge/mfa-required
// - /auth/challenge/mfa-required/passkey (when passkey is preferred)
// - /auth/challenge/mfa-selector (when multiple methods available)

Pattern 2: Single Route with Query Param

All challenges go to one route with a query parameter. Set useSingleChallengeRoute to true.

{
redirects: {
challengeBase: '/auth/challenge',
useSingleChallengeRoute: true
}
}
// Results:
// - /auth/challenge?challenge=VERIFY_EMAIL
// - /auth/challenge?challenge=MFA_REQUIRED

Pattern 3: Custom Routes

Override specific challenge routes using challengeRoutes. Requires importing AuthChallenge enum.

import { AuthChallenge } from '@nauth-toolkit/client';

{
redirects: {
challengeRoutes: {
[AuthChallenge.MFA_REQUIRED]: '/auth/mfa',
[AuthChallenge.VERIFY_EMAIL]: '/verify',
[AuthChallenge.VERIFY_PHONE]: '/verify-phone',
}
}
}

Pattern 4: MFA-Specific Routes

Fine-grained control over MFA navigation using mfaRoutes. Only applies to MFA_REQUIRED challenges.

{
redirects: {
challengeBase: '/auth/challenge',
mfaRoutes: {
passkey: '/auth/passkey', // When preferredMethod is 'passkey'
selector: '/auth/choose-method', // When multiple methods available
default: '/auth/verify-code', // For SMS, email, TOTP
}
}
}

Pattern 5: Dialog-Based (No Navigation)

Handle challenges with dialogs instead of navigation. Use onAuthResponse callback to disable auto-navigation.

{
onAuthResponse: (response, context) => {
if (response.challengeName) {
// Open dialog/modal instead of navigating
dialog.open(ChallengeComponent, { data: response });
} else if (response.user) {
router.navigate(['/dashboard']);
}
};
}

Pattern 6: Custom Navigation Handler

Use custom navigation function for framework-specific routing. Only used when onAuthResponse is not provided.

{
navigationHandler: (url: string) => {
// Angular Router
inject(Router).navigateByUrl(url);

// React Router
// navigate(url);

// Vue Router
// router.push(url);
};
}

See Challenge Handling Guide for complete examples and implementation details.

AuthResponseContext

Context object provided to the onAuthResponse callback. Contains information about the authentication operation that triggered the response.

PropertyTypeDescription
source'login' | 'signup' | 'social' | 'challenge' | 'refresh'Source of the auth operation
providerstring | undefinedOAuth provider name (only present when source is 'social')
fromGuardboolean | undefinedWhether this was triggered from a route guard

Example:

{
onAuthResponse: (response, context) => {
if (context.source === 'social') {
console.log(`Social login via ${context.provider}`);
}

if (context.fromGuard) {
// Handle guard-triggered auth
}

if (response.challengeName) {
// Handle challenge
}
};
}

Token Delivery Modes

ModeDescriptionUse Case
cookiesTokens stored in HTTP-only cookies by backendWeb apps (recommended)
jsonTokens returned in response body, stored client-sideMobile/native apps
Backend Hybrid Deployment

When your backend supports both web and mobile (hybrid deployment), it exposes separate endpoints:

  • Web: /auth/* (cookies mode)
  • Mobile: /mobile/auth/* (JSON mode)

The frontend chooses ONE mode and the appropriate baseUrl based on the platform.

Example

import { NAuthClient, BrowserStorage } from '@nauth-toolkit/client';

const client = new NAuthClient({
// Required
baseUrl: 'https://api.example.com/auth',
tokenDelivery: 'cookies',

// Optional - redirect URLs (platform-agnostic)
redirects: {
loginSuccess: '/',
sessionExpired: '/login',
oauthError: '/login',
challengeBase: '/auth/challenge',
},

// Optional - custom storage
storage: new BrowserStorage(window.sessionStorage),

// Optional - CSRF config
csrf: {
cookieName: 'nauth_csrf_token',
headerName: 'x-csrf-token',
},

// Optional - callbacks
onAuthStateChange: (user) => {
console.log('Auth state changed:', user?.email);
},
onTokenRefresh: () => {
console.log('Tokens refreshed');
},

// Optional - debugging
debug: process.env.NODE_ENV === 'development',
});

Custom Endpoints

Override default endpoint paths if your backend uses different routes. The endpoints property accepts a Partial<NAuthEndpoints>, allowing you to override only the endpoints you need.

import { NAuthClient } from '@nauth-toolkit/client';

const client = new NAuthClient({
baseUrl: 'https://api.example.com/auth',
tokenDelivery: 'cookies',
onSessionExpired: () => {},
endpoints: {
login: '/signin', // Default: /login
signup: '/register', // Default: /signup
logout: '/signout', // Default: /logout
refresh: '/token/refresh', // Default: /refresh
},
});

See NAuthEndpoints for the complete interface and all available endpoints.

Default Endpoints

See NAuthEndpoints for the complete interface and all default values.

EndpointDefault Path
auditHistory/audit/history
changePassword/change-password
confirmForgotPassword/forgot-password/confirm
forgotPassword/forgot-password
getChallengeData/challenge/challenge-data
getSetupData/challenge/setup-data
isTrustedDevice/is-trusted-device
login/login
logout/logout
logoutAll/logout/all
mfaBackupCodes/mfa/backup-codes/generate
mfaDevices/mfa/devices
mfaPreferred/mfa/preferred-method
mfaRemove/mfa/method
mfaSetupData/mfa/setup-data
mfaStatus/mfa/status
mfaVerifySetup/mfa/verify-setup
profile/profile
refresh/refresh
requestPasswordChange/request-password-change
resendCode/challenge/resend
respondChallenge/respond-challenge
signup/signup
socialExchange/social/exchange
socialLink/social/link
socialLinked/social/linked
socialRedirectStart/social/:provider/redirect
socialUnlink/social/unlink
socialVerify/social/:provider/verify
trustDevice/trust-device
updateProfile/profile

NAuthStorageAdapter

Interface for custom storage implementations. See NAuthStorageAdapter for complete documentation.

interface NAuthStorageAdapter {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
clear(): Promise<void>;
}

Built-in Adapters

The SDK provides two built-in storage adapters that implement NAuthStorageAdapter:

AdapterDescriptionExport
BrowserStorageUses localStorage (default) or sessionStorageimport { BrowserStorage } from '@nauth-toolkit/client'
InMemoryStorageIn-memory storage (for SSR or testing)import { InMemoryStorage } from '@nauth-toolkit/client'

BrowserStorage

Browser storage adapter that wraps localStorage or sessionStorage. This is the default storage adapter for web applications.

import { BrowserStorage } from '@nauth-toolkit/client';

// Use localStorage (default)
const storage = new BrowserStorage();

// Use sessionStorage
const storage = new BrowserStorage(window.sessionStorage);

InMemoryStorage

In-memory storage adapter for server-side rendering (SSR), testing, or environments without Web Storage API.

import { InMemoryStorage } from '@nauth-toolkit/client';

const storage = new InMemoryStorage();

See NAuthStorageAdapter for interface details and custom implementation examples.

Custom Adapter Example

import { NAuthStorageAdapter } from '@nauth-toolkit/client';
import { Preferences } from '@capacitor/preferences';

// Capacitor storage adapter for mobile apps
class CapacitorStorage implements NAuthStorageAdapter {
async getItem(key: string): Promise<string | null> {
const { value } = await Preferences.get({ key });
return value;
}

async setItem(key: string, value: string): Promise<void> {
await Preferences.set({ key, value });
}

async removeItem(key: string): Promise<void> {
await Preferences.remove({ key });
}

async clear(): Promise<void> {
await Preferences.clear();
}
}

const client = new NAuthClient({
baseUrl: 'https://api.example.com/auth',
tokenDelivery: 'json', // Mobile apps use JSON mode
storage: new CapacitorStorage(),
onSessionExpired: () => {},
});

Angular Example

For Angular applications, use a simple configuration object without factory methods:

import { ApplicationConfig } from '@angular/core';
import { NAUTH_CLIENT_CONFIG, type NAuthClientConfig } from '@nauth-toolkit/client-angular';
import { environment } from '../environments/environment';

export const appConfig: ApplicationConfig = {
providers: [
{
provide: NAUTH_CLIENT_CONFIG,
useValue: {
baseUrl: `${environment.apiBaseUrl}/auth`,
tokenDelivery: 'cookies',
debug: true,
redirects: {
loginSuccess: '/',
signupSuccess: '/onboarding',
sessionExpired: '/login',
oauthError: '/login',
challengeBase: '/auth/challenge',
},
} satisfies NAuthClientConfig,
},
],
};

The socialRedirectCallbackGuard and authInterceptor automatically use the redirect URLs from the config:

import { Routes } from '@angular/router';
import { authGuard, socialRedirectCallbackGuard } from '@nauth-toolkit/client-angular';

export const routes: Routes = [
{
path: 'auth/callback',
canActivate: [socialRedirectCallbackGuard], // Uses config.redirects
children: [],
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [authGuard()],
},
];