useAuth

Authentication state management hook for user sessions and authentication flows.

Framework Support: Available in React, Vue, Angular, Next.js, Nuxt, Solid, and Svelte SDKs

Installation

npm install @heliorim/sdk-react
# or for Vue
npm install @heliorim/sdk-vue

Import

// React
import { useAuth } from '@heliorim/sdk-react';

// Vue
import { useAuth } from '@heliorim/sdk-vue';

// Angular
import { useAuth } from '@heliorim/sdk-angular';

Type Signature

interface AuthState {
  isLoading: boolean;
  isAuthenticated: boolean;
  user: {
    id: string;
    email?: string;
    name?: string;
    createdAt: number;
  } | null;
  session: Session | null;
  error: Error | null;
}

interface AuthActions {
  login: (email?: string) => Promise<void>;
  logout: () => Promise<void>;
  refreshSession: () => Promise<void>;
  clearError: () => void;
}

type UseAuthReturn = AuthState & AuthActions;

function useAuth(): UseAuthReturn;

Usage Example

function LoginComponent() {
  const {
    isAuthenticated,
    isLoading,
    user,
    error,
    login,
    logout,
    clearError
  } = useAuth();

  const handleLogin = async () => {
    try {
      await login('user@example.com');
      // User is now authenticated
    } catch (err) {
      console.error('Login failed:', err);
    }
  };

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isAuthenticated && user) {
    return (
      <div>
        <p>Welcome, {user.email}!</p>
        <button onClick={logout}>Sign Out</button>
      </div>
    );
  }

  return (
    <div>
      {error && (
        <div className="error">
          {error.message}
          <button onClick={clearError}>Dismiss</button>
        </div>
      )}
      <button onClick={handleLogin}>Sign In with Passkey</button>
    </div>
  );
}

Return Values

isLoading

boolean - Indicates if authentication operations are in progress

isAuthenticated

boolean - Current authentication status

user

User | null - Authenticated user object with id, email, name, and createdAt

session

Session | null - Current session object with token and expiry information

error

Error | null - Any authentication error that occurred

login(email?)

Promise<void> - Initiates passkey authentication flow. Email is optional for returning users.

logout()

Promise<void> - Ends the current session and clears authentication state

refreshSession()

Promise<void> - Refreshes the current session token before expiry

clearError()

void - Clears any authentication errors from state

Common Patterns

Protected Routes

function ProtectedRoute({ children }) {
  const { isAuthenticated, isLoading } = useAuth();

  if (isLoading) return <LoadingSpinner />;
  if (!isAuthenticated) return <Navigate to="/login" />;

  return children;
}

Auto-refresh Sessions

function App() {
  const { refreshSession, session } = useAuth();

  useEffect(() => {
    if (!session) return;

    // Refresh 5 minutes before expiry
    const msUntilExpiry = session.expiresAt - Date.now();
    const refreshTime = msUntilExpiry - (5 * 60 * 1000);

    if (refreshTime > 0) {
      const timer = setTimeout(refreshSession, refreshTime);
      return () => clearTimeout(timer);
    }
  }, [session, refreshSession]);

  return <AppContent />;
}

Conditional Authentication

function ConditionalAuth() {
  const { isAuthenticated, login } = useAuth();
  const [email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Only require email for first-time users
    if (email) {
      await login(email);
    } else {
      // Returning user - browser will show passkey picker
      await login();
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email (optional for returning users)"
      />
      <button type="submit">Sign In</button>
    </form>
  );
}

Error Handling

const { login, error, clearError } = useAuth();

// Common error types
try {
  await login('user@example.com');
} catch (err) {
  if (err.code === 'NotAllowedError') {
    // User cancelled the passkey ceremony
  } else if (err.code === 'InvalidStateError') {
    // Authenticator not available
  } else if (err.code === 'NetworkError') {
    // Network connection issue
  } else {
    // Other error
  }
}

TypeScript Usage

import { useAuth, type UseAuthReturn } from '@heliorim/sdk-react';

interface AuthContextValue extends UseAuthReturn {
  customMethod: () => void;
}

function useExtendedAuth(): AuthContextValue {
  const auth = useAuth();

  const customMethod = () => {
    // Custom logic using auth state
    if (auth.isAuthenticated) {
      console.log('User:', auth.user?.email);
    }
  };

  return {
    ...auth,
    customMethod
  };
}

Server-Side Rendering (SSR)

Note: WebAuthn APIs are browser-only. For SSR frameworks like Next.js or Nuxt:

  • Authentication operations must run client-side
  • Use session cookies for server-side auth state
  • Hydrate auth state from cookies on mount

Related Hooks