JavaScript / React SDK

Type-safe authentication for Next.js and React applications. Zero dependencies beyond React.

Installation#

npm install @auth-saas/client

AuthClient#

The core client class. Create one instance per app and share it via AuthProvider.

import { AuthClient } from '@auth-saas/client';

const authClient = new AuthClient({
  clientId: process.env.NEXT_PUBLIC_AUTH_CLIENT_ID!, // required
  baseUrl:  'https://your-domain.com/api/v1',        // optional, defaults to /api/v1
});
MethodReturnsDescription
register(params)Promise<AuthSession>Register + auto sign in
login(params)Promise<AuthSession>Sign in user
logout()Promise<void>Revoke all sessions
refreshTokens()Promise<AuthTokens>Manual token refresh (deduped)
authFetch(url, init)Promise<Response>Fetch with auto JWT + refresh
getSession()AuthSession | nullCurrent session
getUser()AuthUser | nullCurrent user
isAuthenticated()booleanTrue if session not expired
on(event, fn)() => voidSubscribe to auth events

AuthProvider#

Wrap your app (or a subtree) with AuthProvider to make auth available via hooks.

app/layout.tsx
import { AuthProvider } from '@auth-saas/client/react';
import { authClient } from '@/lib/auth-client'; // your singleton

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AuthProvider client={authClient}>
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

useAuth()#

Access auth state and actions anywhere inside AuthProvider.

import { useAuth } from '@auth-saas/client/react';

const {
  user,            // AuthUser | null
  session,         // AuthSession | null
  isAuthenticated, // boolean
  isLoading,       // boolean — true during login/register/logout
  login,           // (params: LoginParams) => Promise<void>
  register,        // (params: RegisterParams) => Promise<void>
  logout,          // () => Promise<void>
  client,          // AuthClient — direct access if needed
} = useAuth();
Full example
'use client';
import { useAuth } from '@auth-saas/client/react';
import { useState } from 'react';

export function AuthForm() {
  const { login, register, logout, user, isLoading } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  if (user) {
    return (
      <div>
        <p>Signed in as {user.email}</p>
        <button onClick={logout}>Sign out</button>
      </div>
    );
  }

  return (
    <form onSubmit={e => { e.preventDefault(); login({ email, password }); }}>
      <input value={email}    onChange={e => setEmail(e.target.value)}    placeholder="Email" />
      <input value={password} onChange={e => setPassword(e.target.value)} placeholder="Password" type="password" />
      <button type="submit" disabled={isLoading}>Sign in</button>
    </form>
  );
}

useAuthFetch()#

A fetch wrapper that automatically attaches the JWT and handles token refresh transparently.

import { useAuthFetch } from '@auth-saas/client/react';

function MyComponent() {
  const authFetch = useAuthFetch();

  async function loadData() {
    // JWT is attached automatically.
    // On 401, token is refreshed and the request is retried once.
    const res = await authFetch('/api/my-protected-endpoint');
    const data = await res.json();
  }
}

Events#

Subscribe to auth lifecycle events via client.on(). Unsubscribe by calling the returned function.

const unsubscribe = authClient.on('sessionExpired', () => {
  // Redirect to login, show toast, etc.
  toast.error('Your session has expired. Please sign in again.');
  router.push('/login');
});

// Clean up
unsubscribe();
EventPayloadFired when
signedInAuthSessionSuccessful login or register
signedOutnulllogout() called
tokenRefreshedAuthSessionAccess token silently refreshed
sessionExpirednullRefresh failed — user must re-authenticate

TypeScript types#

import type {
  AuthConfig,    // { clientId: string; baseUrl?: string }
  AuthSession,   // { user, tokens, expiresAt }
  AuthUser,      // { id, email, name, roles, emailVerified }
  AuthTokens,    // { accessToken, refreshToken, expiresIn }
  AuthEvent,     // 'signedIn' | 'signedOut' | 'tokenRefreshed' | 'sessionExpired'
  LoginParams,   // { email, password }
  RegisterParams // { email, password, name? }
} from '@auth-saas/client';

C# SDK#

Note

The C# / Blazor SDK is in development. It will be published as a NuGet package with full ASP.NET Core DI integration and [Authorize] attribute support. Check back soon.