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.

AuthProvider

React context provider that wraps your application and provides authentication state to all components.

Overview

The AuthProvider component creates a React context that manages authentication state, handles automatic token refresh, and provides auth methods to all child components via hooks.
Required for Client Hooks
All client-side hooks (useAuth, useSession, useMfa) require AuthProvider to be present in the component tree.

Props

interface AuthProviderProps {
  children: ReactNode;
  config: AuthSafeConfig;
  initialSession?: AuthSession | null;
}

config

interface AuthSafeConfig {
  clientId: string; // OAuth client ID
  domain: string; // AuthSafe domain
  redirectUri?: string; // Default: /api/auth/callback
  scopes?: string[]; // Default: ['openid', 'email', 'profile']
  cookies?: {
    prefix?: string; // Default: 'authsafe'
    domain?: string;
    path?: string; // Default: '/'
    secure?: boolean; // Default: true in production
    sameSite?: 'strict' | 'lax' | 'none'; // Default: 'lax'
  };
  session?: {
    maxAge?: number; // Session duration in seconds (default: 3600)
    autoRefresh?: boolean; // Default: true
  };
}

initialSession

Pass the server-side rendered session to avoid hydration flicker:
interface AuthSession {
  userId: string;
  email: string;
  name?: string;
  emailVerified: boolean;
  organizationId: string;
  issuedAt: number;
  expiresAt: number;
}

Usage

App Router

// app/layout.tsx
import { AuthProvider } from 'authsafe-nextjs/client';
import { getAuth, initAuthSafe } from 'authsafe-nextjs/server';

// Initialize on server-side
initAuthSafe({
  clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
  domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
  clientSecret: process.env.AUTHSAFE_CLIENT_SECRET,
});

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // Get session server-side
  const session = await getAuth();

  return (
    <html lang="en">
      <body>
        <AuthProvider
          config={{
            clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
            domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
          }}
          initialSession={session}
        >
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

Pages Router

// pages/_app.tsx
import { AuthProvider } from 'authsafe-nextjs/client';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <AuthProvider
      config={{
        clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
        domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
      }}
      initialSession={pageProps.session}
    >
      <Component {...pageProps} />
    </AuthProvider>
  );
}

Features

Automatic Token Refresh

AuthProvider automatically schedules token refresh 5 minutes before expiration:
// Automatic refresh happens in the background
<AuthProvider config={config} initialSession={session}>
  {/* Your app - tokens stay fresh automatically */}
</AuthProvider>

Session Synchronization

Session state is synchronized between server and client on mount:
// Server-rendered session is passed to client
const session = await getAuth(); // Server
<AuthProvider initialSession={session}> {/* Client hydrates with same state */}

Global Auth State

All children can access auth state via hooks:
<AuthProvider config={config}>
  <Header /> {/* Can use useAuth() */}
  <Dashboard /> {/* Can use useSession() */}
  <MfaSettings /> {/* Can use useMfa() */}
</AuthProvider>

Advanced Configuration

Custom Cookie Settings

<AuthProvider
  config={{
    clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
    domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
    cookies: {
      prefix: 'myapp', // Custom prefix
      domain: '.example.com', // Share across subdomains
      secure: true, // HTTPS only
      sameSite: 'strict', // CSRF protection
    },
  }}
>
  {children}
</AuthProvider>

Custom Session Duration

<AuthProvider
  config={{
    clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
    domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
    session: {
      maxAge: 7200, // 2 hours
      autoRefresh: true, // Enable auto-refresh
    },
  }}
>
  {children}
</AuthProvider>

Custom Scopes

<AuthProvider
  config={{
    clientId: process.env.NEXT_PUBLIC_AUTHSAFE_CLIENT_ID!,
    domain: process.env.NEXT_PUBLIC_AUTHSAFE_DOMAIN!,
    scopes: ['openid', 'email', 'profile', 'offline_access', 'admin'],
  }}
>
  {children}
</AuthProvider>

Context Value

The AuthProvider exposes the following via useAuthContext():
interface AuthContextValue {
  isAuthenticated: boolean;
  isLoading: boolean;
  user: AuthSession | null;
  error: Error | null;
  signIn: (returnTo?: string) => Promise<void>;
  signOut: (returnTo?: string) => Promise<void>;
  refreshSession: () => Promise<void>;
  config: AuthSafeConfig;
}
Note: Use useAuth() hook instead of useAuthContext() directly for better ergonomics.

Best Practices

  1. Always pass initialSession to avoid authentication flicker during hydration
  2. Initialize on server-side with initAuthSafe() in your root layout
  3. Use environment variables for client ID and domain
  4. Enable autoRefresh for seamless UX
  5. Set appropriate maxAge based on your security requirements

Troubleshooting

Hydration Mismatch

If you see hydration errors, make sure to pass initialSession:
// ✅ Correct
const session = await getAuth();
<AuthProvider initialSession={session}>

// ❌ Wrong - will cause hydration mismatch
<AuthProvider>

"useAuthContext must be used within AuthProvider"

This error means you're using a hook outside of AuthProvider:
// ✅ Correct
<AuthProvider config={config}>
  <Component /> {/* Can use useAuth() */}
</AuthProvider>

// ❌ Wrong
<Component /> {/* No AuthProvider above */}

Related

  • useAuth() - Access auth state and methods
  • useSession() - Get current session
  • Server Authentication - getAuth() for Server Components