@nexefy/auth-react
v1.4.0
Published
React hooks for Nexefy Auth SDK
Downloads
272
Readme
@nexefy/auth-react
React hooks for Nexefy Auth SDK - OAuth 2.1 authentication made easy.
Installation
npm install @nexefy/auth-react @nexefy/auth-client
# or
pnpm add @nexefy/auth-react @nexefy/auth-clientQuick Start
import { createNexefyClient } from '@nexefy/auth-client'
import { NexefyProvider, useNexefyAuth } from '@nexefy/auth-react'
// Create client
const nexefy = createNexefyClient({
authUrl: 'https://auth.nexefy.com',
clientId: 'your-client-id',
organisationSlug: 'your-org',
scopes: ['openid', 'profile', 'email', 'offline_access']
})
// Wrap your app
function App() {
return (
<NexefyProvider client={nexefy}>
<YourApp />
</NexefyProvider>
)
}
// Use in components
function YourApp() {
const { user, isAuthenticated, isLoading, signIn, signOut } = useNexefyAuth()
// Do NOT route to login while loading — a silent refresh may be in flight.
if (isLoading) {
return <div>Loading…</div>
}
if (!isAuthenticated) {
return <button onClick={() => signIn()}>Sign In</button>
}
return (
<div>
<h1>Welcome {user?.name}</h1>
<button onClick={() => signOut()}>Sign Out</button>
</div>
)
}Hooks
useNexefyAuth()
Main authentication hook.
const {
// state
user,
session,
isLoading,
isAuthenticated,
sessionStatus, // 'loading' | 'authenticated' | 'unauthenticated' | 'recoverable'
authError, // last terminal refresh failure (e.g. invalid_grant), or null
// methods
signIn, // (options?) => Promise<void> — begins OAuth redirect
handleCallback, // (url?) => Promise<boolean>
signOut, // (options?) => Promise<void> — accepts { federated }
refreshToken, // () => Promise<boolean>
authenticatedFetch,
getAccessToken,
getIdToken,
client
} = useNexefyAuth()isAuthenticated stays stable across access-token expiry: it remains true while a recoverable silent refresh is in flight, so the UI does not flash the login screen every hour. Gate route guards on isLoading / sessionStatus rather than redirecting on !isAuthenticated alone.
Switching users
const { signOut, signIn } = useNexefyAuth()
// Force the IDP login screen so a different user can sign in
await signOut()
await signIn({ prompt: 'login' })
// Or end the IDP SSO session entirely (federated logout)
await signOut({ federated: true })Terminal refresh failures
The provider listens for tokenRefreshFailed. A terminal invalid_grant clears the session and surfaces via authError; transient (network/5xx) failures are ignored so the user is not logged out unnecessarily.
useNexefyUser()
User-specific data hook.
const {
user,
isLoading,
organisationSlug,
teams,
role
} = useNexefyUser()Compatibility
Requires @nexefy/auth-client@^1.4.0 (for hydrateSession() and federated sign-out). The provider falls back gracefully on older clients but sessionStatus / federated logout require 1.4.0+.
License
MIT
