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.

useAuth()

Main authentication hook for client components. Provides authentication state and methods.

Import

'use client';

import { useAuth } from 'authsafe-nextjs/client';

Return Value

interface UseAuthReturn {
  isAuthenticated: boolean;
  isLoading: boolean;
  user: AuthSession | null;
  error: Error | null;
  signIn: (options?: SignInOptions) => Promise<void>;
  signOut: (options?: SignOutOptions) => Promise<void>;
  refreshSession: () => Promise<void>;
}

Properties

isAuthenticated - Whether user is authenticated isLoading - Whether auth state is loading user - Current user session or null
interface AuthSession {
  userId: string;
  email: string;
  name?: string;
  emailVerified: boolean;
  organizationId: string;
  issuedAt: number;
  expiresAt: number;
}
error - Authentication error if any

Methods

signIn(options?) - Redirect to sign in
interface SignInOptions {
  redirectTo?: string; // Redirect URL after sign in
  scopes?: string[]; // Additional scopes
  state?: string; // Custom state parameter
}
signOut(options?) - Sign out and clear session
interface SignOutOptions {
  redirectTo?: string; // Redirect URL after sign out
}
refreshSession() - Manually refresh the session

Usage Examples

Basic Authentication Check

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function Header() {
  const { isAuthenticated, user, signIn, signOut } = useAuth();

  if (!isAuthenticated) {
    return <button onClick={() => signIn()}>Sign In</button>;
  }

  return (
    <div>
      <span>Welcome, {user.email}</span>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}

Loading State

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function UserProfile() {
  const { isLoading, isAuthenticated, user } = useAuth();

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

  if (!isAuthenticated) {
    return <div>Please sign in</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

Sign In with Redirect

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function LoginButton() {
  const { signIn } = useAuth();

  const handleLogin = () => {
    signIn({ redirectTo: '/dashboard' });
  };

  return <button onClick={handleLogin}>Sign In to Dashboard</button>;
}

Sign Out with Custom Redirect

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function LogoutButton() {
  const { signOut } = useAuth();

  const handleLogout = () => {
    signOut({ redirectTo: '/goodbye' });
  };

  return <button onClick={handleLogout}>Sign Out</button>;
}

Manual Session Refresh

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function RefreshButton() {
  const { refreshSession, user } = useAuth();

  const handleRefresh = async () => {
    try {
      await refreshSession();
      alert('Session refreshed!');
    } catch (error) {
      alert('Refresh failed');
    }
  };

  return (
    <div>
      <p>
        Token expires at: {new Date(user.expiresAt * 1000).toLocaleString()}
      </p>
      <button onClick={handleRefresh}>Refresh Now</button>
    </div>
  );
}

Error Handling

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function AuthStatus() {
  const { isAuthenticated, error } = useAuth();

  if (error) {
    return <div className="error">Authentication Error: {error.message}</div>;
  }

  return isAuthenticated ? (
    <div>Authenticated</div>
  ) : (
    <div>Not authenticated</div>
  );
}

Conditional Rendering

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function ConditionalContent() {
  const { isAuthenticated, isLoading, user } = useAuth();

  if (isLoading) {
    return <Spinner />;
  }

  return (
    <>
      {isAuthenticated ? (
        <div>
          <h1>Welcome {user.name}</h1>
          <AdminPanel />
        </div>
      ) : (
        <div>
          <h1>Please Sign In</h1>
          <PublicContent />
        </div>
      )}
    </>
  );
}

with Custom Scopes

'use client';

import { useAuth } from 'authsafe-nextjs/client';

export function AdminLogin() {
  const { signIn } = useAuth();

  const handleAdminLogin = () => {
    signIn({
      scopes: ['openid', 'profile', 'email', 'admin', 'write:users'],
      redirectTo: '/admin',
    });
  };

  return <button onClick={handleAdminLogin}>Admin Sign In</button>;
}

Complete Example

'use client';

import { useAuth } from 'authsafe-nextjs/client';
import { useState } from 'react';

export function AuthenticatedApp() {
  const { isAuthenticated, isLoading, user, signIn, signOut, error } =
    useAuth();
  const [showProfile, setShowProfile] = useState(false);

  // Loading state
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="p-4 bg-red-100 border border-red-400 text-red-700 rounded">
        <h2>Authentication Error</h2>
        <p>{error.message}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

  // Not authenticated
  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen">
        <h1 className="text-3xl font-bold mb-4">Welcome</h1>
        <p className="mb-8">Please sign in to continue</p>
        <button
          onClick={() => signIn({ redirectTo: '/dashboard' })}
          className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Sign In
        </button>
      </div>
    );
  }

  // Authenticated
  return (
    <div>
      <header className="flex items-center justify-between p-4 bg-white shadow">
        <h1 className="text-xl font-bold">My App</h1>
        <div className="flex items-center gap-4">
          <button
            onClick={() => setShowProfile(!showProfile)}
            className="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200"
          >
            {user.name || user.email}
          </button>
          <button
            onClick={() => signOut()}
            className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
          >
            Sign Out
          </button>
        </div>
      </header>

      {showProfile && (
        <div className="p-4 bg-gray-50 border-b">
          <h2 className="font-semibold mb-2">Profile</h2>
          <p>Email: {user.email}</p>
          <p>Name: {user.name || 'N/A'}</p>
          <p>Email Verified: {user.emailVerified ? 'Yes' : 'No'}</p>
          <p>Organization: {user.organizationId}</p>
        </div>
      )}

      <main className="p-8">
        <h2 className="text-2xl font-bold mb-4">Dashboard</h2>
        <p>Welcome back, {user.name}!</p>
      </main>
    </div>
  );
}

Related

  • AuthProvider - Required provider for useAuth
  • useSession() - Simplified session access
  • Pre-built Components - SignInButton, SignOutButton
  • Server Authentication - getAuth() for Server Components