Skip to main content

React SDK

The Idenplane React SDK provides React-specific bindings for the idenplane-sdk, including AuthProvider, useAuth, useUser, usePermissions hooks, and a ProtectedRoute component for declarative authentication.

Installation​

npm install idenplane-sdk

Quick Start​

Basic Setup​

import { AuthProvider, useAuth, useUser, usePermissions } from 'idenplane-sdk/react';

function App() {
return (
<AuthProvider
serverUrl="http://localhost:3000"
realm="my-realm"
clientId="my-app"
redirectUri="http://localhost:5173/callback"
onLogin={(tokens) => console.log('Logged in!', tokens)}
onLogout={() => console.log('Logged out!')}
onError={(err) => console.error('Auth error:', err)}
>
<Main />
</AuthProvider>
);
}

function Main() {
const { isAuthenticated, isLoading, login, logout, getToken } = useAuth();
const user = useUser();
const { hasRole, hasPermission, roles } = usePermissions();

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

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

return (
<div>
<h1>Welcome, {user?.name}!</h1>
<p>Email: {user?.email}</p>
<p>Your roles: {roles.join(', ')}</p>

{hasRole('admin') && (
<p>You have admin privileges.</p>
)}

{hasPermission('read:reports') && (
<p>You can access reports.</p>
)}

<button onClick={() => logout()}>
Sign Out
</button>
</div>
);
}

AuthProvider​

The AuthProvider is the root component that initializes authentication and provides auth state to all child components.

Props​

PropTypeRequiredDescription
serverUrlstringYes*Idenplane server URL
realmstringYes*Realm name
clientIdstringYes*OAuth2 client ID
redirectUristringYes*Redirect URI after login
clientIdenplaneClientYes*Pre-built client instance
scopestring[]NoOAuth2 scopes (default: ['openid', 'profile', 'email'])
autoHandleCallbackbooleanNoAuto-handle callback when URL has ?code= (default: true)
onReady(authenticated: boolean) => voidNoCalled when initialization completes
onLogin(tokens: TokenResponse) => voidNoCalled on successful login
onLogout() => voidNoCalled on logout
onError(error: Error) => voidNoCalled on authentication error
onTokenRefresh(tokens: TokenResponse) => voidNoCalled after token refresh

*Either a client prop or all of serverUrl, realm, clientId, and redirectUri are required.

With Inline Config​

<AuthProvider
serverUrl="http://localhost:3000"
realm="my-realm"
clientId="my-app"
redirectUri="http://localhost:5173/callback"
scope={['openid', 'profile', 'email', 'custom:scope']}
onReady={(authed) => console.log('Ready! Authenticated:', authed)}
onLogin={(tokens) => {
console.log('Access token:', tokens.access_token);
}}
>
<App />
</AuthProvider>

With Pre-built Client​

For more control over the client configuration:

import { IdenplaneClient } from 'idenplane-sdk';
import { AuthProvider } from 'idenplane-sdk/react';

const client = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:5173/callback',
refreshStrategy: 'rotation', // 'rotation' | 'silent' | 'eager'
storage: 'sessionStorage', // 'sessionStorage' | 'localStorage' | 'memory'
refreshBuffer: 30, // seconds before expiry to trigger refresh
autoRefresh: true, // enable automatic refresh
});

function App() {
return (
<AuthProvider client={client}>
<Main />
</AuthProvider>
);
}

useAuth Hook​

The useAuth hook provides access to authentication state and actions:

const {
client, // The IdenplaneClient instance
isAuthenticated, // boolean - whether user is authenticated
isLoading, // boolean - whether auth state is loading
user, // UserInfo | null - current user info
login, // (options?) => Promise<void> - initiate login
logout, // () => Promise<void> - sign out
getToken, // () => string | null - get current access token
} = useAuth();

Example: Login Options​

function LoginButton() {
const { login } = useAuth();

const handleLogin = async () => {
try {
await login({ scope: ['openid', 'profile', 'email', 'custom:scope'] });
} catch (error) {
console.error('Login failed:', error);
}
};

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

Example: Accessing the Token​

function TokenDisplay() {
const { getToken, isAuthenticated } = useAuth();

if (!isAuthenticated) return null;

return (
<div>
<p>Your access token:</p>
<code>{getToken()?.substring(0, 20)}...</code>
</div>
);
}

useUser Hook​

The useUser hook returns the current user's information from the ID token claims:

const user = useUser();
// Returns: UserInfo | null

interface UserInfo {
sub: string; // User ID
preferred_username?: string;
name?: string; // Display name
given_name?: string;
family_name?: string;
email?: string; // Email address
email_verified?: boolean;
[key: string]: unknown; // Any other claim in the ID token
}
// Roles are not on UserInfo: use usePermissions() or useRoles().

Example: User Profile Card​

function UserProfile() {
const user = useUser();

if (!user) {
return <div>Not signed in</div>;
}

return (
<div className="profile-card">
{typeof user.picture === 'string' && (
<img src={user.picture} alt={user.name} />
)}
<h2>{user.name || 'User'}</h2>
<p>{user.email}</p>
{user.email_verified ? (
<span>Email verified</span>
) : (
<span>Email not verified</span>
)}
</div>
);
}

usePermissions Hook​

The usePermissions hook provides role and permission checking:

const {
roles, // string[] - the user's realm roles
hasRole, // (role: string) => boolean - realm role check
hasPermission, // (permission: string) => boolean
} = usePermissions();

For client roles, useRoles() returns { hasRealmRole, hasClientRole, realmRoles, getClientRoles }.

Example: Role-Based UI​

function Dashboard() {
const { hasRole, hasPermission } = usePermissions();

return (
<div>
<h1>Dashboard</h1>

{/* Admin-only section */}
{hasRole('admin') && (
<section>
<h2>Admin Panel</h2>
<a href="/admin">Go to Admin</a>
</section>
)}

{/* Content with multiple role check */}
{['editor', 'admin'].some(hasRole) && (
<section>
<h2>Content Editor</h2>
<button>Edit Content</button>
</section>
)}

{/* Permission-based access */}
{hasPermission('read:reports') && (
<section>
<h2>Reports</h2>
<button>View Reports</button>
</section>
)}

{/* Fallback for unauthorized */}
{!hasRole('admin') && (
<p>You don't have admin access.</p>
)}
</div>
);
}

Example: Multi-Role Check​

function ModeratorTools() {
const { hasRole } = usePermissions();

const canAccessModeration = ['moderator', 'content-editor'].every(hasRole);

if (!canAccessModeration) {
return <div>You need both moderator and content-editor roles.</div>;
}

return (
<div>
<h2>Moderation Tools</h2>
{/* Moderation UI */}
</div>
);
}

ProtectedRoute Component​

The ProtectedRoute component guards routes that require authentication or specific roles:

import { AuthProvider, ProtectedRoute } from 'idenplane-sdk/react';
import { useNavigate } from 'react-router-dom';

function AdminPage() {
const navigate = useNavigate();

return (
<ProtectedRoute
roles={['admin']}
fallback={<div>Loading...</div>}
onUnauthorized={() => {
navigate('/login');
return null;
}}
onForbidden={() => (
<div>
<h2>Access Denied</h2>
<p>You need admin privileges to access this page.</p>
<button onClick={() => navigate('/')}>Go Home</button>
</div>
)}
>
<AdminDashboard />
</ProtectedRoute>
);
}

ProtectedRoute Props​

PropTypeRequiredDescription
childrenReactNodeYesContent to render when authorized
rolesstring[]NoRequired roles (user must have all)
fallbackReactNodeNoLoading state while checking auth
onUnauthorized() => ReactNodeNoRendered when not authenticated
onForbidden() => ReactNodeNoRendered when authenticated but lacks roles

Using with React Router​

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { AuthProvider, ProtectedRoute } from 'idenplane-sdk/react';

function App() {
return (
<AuthProvider
serverUrl="http://localhost:3000"
realm="my-realm"
clientId="my-app"
redirectUri="http://localhost:5173/callback"
>
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />

<Route
path="/dashboard"
element={
<ProtectedRoute fallback={<Loading />}>
<DashboardPage />
</ProtectedRoute>
}
/>

<Route
path="/admin"
element={
<ProtectedRoute
roles={['admin']}
fallback={<Loading />}
onForbidden={() => <AccessDenied />}
>
<AdminPage />
</ProtectedRoute>
}
/>
</Routes>
</BrowserRouter>
</AuthProvider>
);
}

Token Refresh Strategies​

Configure how the SDK refreshes tokens via the refreshStrategy option:

StrategyDescription
rotation(default) Uses refresh token grant to get a new access token
eagerLike rotation, but refreshes proactively at 2× the refreshBuffer
silentUses a hidden iframe with prompt=none for silent re-auth

Example: Eager Refresh​

import { IdenplaneClient } from 'idenplane-sdk';
import { AuthProvider } from 'idenplane-sdk/react';

const client = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:5173/callback',
refreshStrategy: 'eager', // refresh 60 seconds before expiry
refreshBuffer: 30, // seconds before expiry to trigger refresh
autoRefresh: true, // enable automatic refresh (default: true)
});

function App() {
return (
<AuthProvider client={client}>
<Main />
</AuthProvider>
);
}

Silent Refresh with iframe​

For the silent strategy, your app's redirect URI page must post a message back to the parent window:

// In your callback page component
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';

function CallbackPage() {
const [searchParams] = useSearchParams();

useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');

if (window.parent !== window) {
window.parent.postMessage(
{
type: 'idenplane:silent_callback',
code,
state,
error,
},
window.location.origin
);
}
}, [searchParams]);

return <div>Completing sign in...</div>;
}

Event System​

Subscribe to SDK events to react to authentication state changes:

import { useEffect } from 'react';
import { useAuth } from 'idenplane-sdk/react';

function AnalyticsTracker() {
const { client } = useAuth();

useEffect(() => {
const handleLogin = (tokens: TokenResponse) => {
console.log('User logged in:', tokens.access_token);
// Track in analytics
analytics.identify(tokens.access_token);
};

const handleLogout = () => {
console.log('User logged out');
// Track in analytics
analytics.reset();
};

const handleTokenRefresh = (tokens: TokenResponse) => {
console.log('Token refreshed');
};

const handleError = (error: Error) => {
console.error('Auth error:', error);
// Report to error tracker
errorTracker.capture(error);
};

const unsubLogin = client.on('login', handleLogin);
const unsubLogout = client.on('logout', handleLogout);
const unsubRefresh = client.on('tokenRefresh', handleTokenRefresh);
const unsubError = client.on('error', handleError);

return () => {
unsubLogin();
unsubLogout();
unsubRefresh();
unsubError();
};
}, [client]);

return null;
}

Available Events​

EventPayloadDescription
loginTokenResponseUser successfully authenticated
logout-User logged out
tokenRefreshTokenResponseAccess token was refreshed
errorErrorAny authentication error, including a failed refresh
readybooleaninit() finished; true if authenticated

TypeScript Support​

The SDK is written in TypeScript and provides full type definitions:

import type {
IdenplaneClient,
IdenplaneConfig,
TokenResponse,
UserInfo,
TokenClaims,
IdenplaneEventMap,
} from 'idenplane-sdk';

// All hooks are fully typed
function MyComponent() {
const user = useUser(); // Type: UserInfo | null
const { isAuthenticated } = useAuth(); // Fully typed
const { hasRole } = usePermissions(); // Fully typed
}

Next Steps​

Quickstart Set up Idenplane and create your first authenticated app

Configuration Learn about all configuration options

API Reference Complete REST API documentation

JavaScript SDK Core SDK for non-React applications


idenplane.com · GitHub · Discord