React and Next.js adapter for AuthOS authentication
npm install @drmhse/authos-react

React adapter for AuthOS - the multi-tenant authentication platform. Provides React hooks, components, and Next.js integration.
``bash`
npm install @drmhse/authos-react
Wrap your app with AuthOSProvider and you're ready to go:
`tsx
import { AuthOSProvider, SignIn, SignedIn, SignedOut, UserButton } from '@drmhse/authos-react';
function App() { You're signed in!
return (
);
}
`
That's it. You now have:
- Email/password authentication with MFA support
- Automatic session management
- User dropdown with logout
- Conditional rendering based on auth state
AuthOS supports two usage modes:
For platform owners and administrators, use without org/service:
`tsx`
For tenant applications with OAuth support, add org and service:
`tsx`
org: 'acme-corp', // Organization slug
service: 'main-app', // Service slug
}}>
To use OAuth providers (GitHub, Google, Microsoft), you need to configure your organization and service in the provider:
`tsx`
org: 'my-org', // Your organization slug
service: 'my-app', // Your service slug
redirectUri: 'https://app.example.com/callback', // Optional
}}>
For advanced use cases, you can pass a pre-configured SsoClient:
`tsx
import { SsoClient } from '@drmhse/sso-sdk';
import { AuthOSProvider } from '@drmhse/authos-react';
// Create client with custom configuration
const client = new SsoClient({
baseURL: 'https://sso.example.com',
storage: customStorage,
});
function App() {
return (
);
}
Or use individual OAuth buttons:
`tsx
import { OAuthButton } from '@drmhse/authos-react';
`
Complete sign-in form with email/password authentication and optional OAuth buttons.
`tsx`
onError={(error) => console.error(error)}
providers={['github', 'google']} // Optional OAuth buttons
showForgotPassword={true} // Show forgot password link
showSignUp={true} // Show sign up link
showDivider={true} // Show "or" divider between OAuth and email form
/>
Props:
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| onSuccess | (user: UserProfile) => void | - | Callback after successful login |onError
| | (error: Error) => void | - | Callback on login error |providers
| | ('github' \| 'google' \| 'microsoft')[] \| false | false | OAuth providers to display |showForgotPassword
| | boolean | true | Show forgot password link |showSignUp
| | boolean | true | Show sign up link |showDivider
| | boolean | true | Show divider between OAuth and email form |className
| | string | - | Custom class name |
Registration form for new users.
`tsx`
onError={(error) => console.error(error)}
orgSlug="my-org" // Optional: override provider config
serviceSlug="my-app" // Optional: override provider config
/>
> [!NOTE]
> The orgSlug and serviceSlug props are optional and will fallback to the values configured in AuthOSProvider. Only use these props if you need to override the provider configuration for a specific use case.
Sign-in component for Magic Links (passwordless).
`tsx`
Sign-in component for Passkeys (WebAuthn).
`tsx`
Conditional rendering based on authentication state. Inspired by Clerk's API.
`tsx
{/ Only shown when user is logged in /}
{/ Only shown when user is logged out /}
`
User menu button with avatar initials and dropdown with profile/signout.
`tsx`
onLogout={() => router.push('/')}
/>
Dropdown to switch between organizations (for multi-tenant users).
When switching organizations, the SDK automatically issues new JWT tokens with the new organization context, enabling seamless multi-tenant switching without re-authentication.
`tsx`
/>
Conditional rendering based on user permissions or roles.
`tsx
`
Individual OAuth provider button. Requires org and service in provider config.
`tsx`
Required for OAuth flows. Handles the redirect from the identity provider by parsing tokens from the URL fragment and setting the session.
`tsx
import { Callback } from '@drmhse/authos-react';
function CallbackPage() {
const router = useRouter();
return (
onError={(error) => console.error(error)}
/>
);
}
`
Props:
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| onSuccess | () => void | - | Callback after session is successfully set |onError
| | (error: Error) => void | - | Callback on error |
Access the AuthOS client and auth state.
`tsx
const { client, config, isAuthenticated, isLoading } = useAuthOS();
// Use the client directly
await client.auth.logout();
`
Get the current user's profile.
`tsx
const { user, isLoading } = useUser();
if (isLoading) return
if (!user) return
return
Welcome, {user.email}
;$3
Get and switch between organizations.
`tsx
const {
currentOrganization,
organizations,
switchOrganization,
isSwitching
} = useOrganization();// Switch to a different org
await switchOrganization('other-org-slug');
`$3
Check user permissions.
`tsx
const canAccessAdmin = usePermission('admin:access');
const canReadOrWrite = useAnyPermission(['read:data', 'write:data']);
const hasFullAccess = useAllPermissions(['read:data', 'write:data', 'delete:data']);if (!canAccessAdmin) return ;
`Next.js Integration
$3
`tsx
// app/layout.tsx
import { AuthOSProvider } from '@drmhse/authos-react';
import { cookies } from 'next/headers';export default async function RootLayout({ children }) {
const cookieStore = cookies();
const token = cookieStore.get('authos_token')?.value;
return (
config={{ baseURL: process.env.NEXT_PUBLIC_SSO_URL! }}
initialSessionToken={token}
>
{children}
);
}
`$3
`ts
// middleware.ts
import { authMiddleware, getJwksUrl } from '@drmhse/authos-react/nextjs';export default authMiddleware({
jwksUrl: getJwksUrl(process.env.NEXT_PUBLIC_SSO_URL!),
protectedRoutes: ['/dashboard/', '/settings/'],
publicRoutes: ['/', '/about', '/pricing'],
signInUrl: '/signin',
});
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
`$3
`tsx
// app/dashboard/page.tsx
import { currentUser } from '@drmhse/authos-react/nextjs';export default async function Dashboard() {
const user = await currentUser();
if (!user) {
redirect('/login');
}
return
Welcome, {user.email};
}
`Configuration Reference
$3
| Prop | Type | Required | Description |
|------|------|----------|-------------|
|
config.baseURL | string | ✅ | AuthOS API URL |
| config.org | string | For OAuth | Organization slug for OAuth flows |
| config.service | string | For OAuth | Service slug for OAuth flows |
| config.redirectUri | string | - | OAuth redirect URI (defaults to origin + '/callback') |
| config.afterSignInUrl | string | - | Redirect URL after sign-in |
| config.afterSignUpUrl | string | - | Redirect URL after sign-up |
| config.storage | TokenStorage | - | Custom token storage |
| client | SsoClient | - | Use existing client instance |
| initialSessionToken | string | - | SSR token for hydration |Styling
AuthOS components come with polished default styling out of the box, similar to best-in-class auth providers. The styling is fully customizable via the
appearance option or by overriding CSS variables.$3
You can customize the theme colors, fonts, and more by passing an
appearance object to AuthOSProvider.`tsx
baseURL: '...',
appearance: {
variables: {
colorPrimary: '#0066cc',
colorBackground: '#f5f5f5',
borderRadius: '0.25rem',
fontFamily: 'Inter, sans-serif',
},
},
}}>
`$3
You can also override these CSS variables in your own stylesheet:
`css
:root {
--authos-color-primary: #0066cc;
--authos-border-radius: 4px;
}
`$3
If you prefer to completely style the components yourself, you can target the data attributes. The default styles have low specificity, so your CSS classes will easily override them.
`css
[data-authos-signin] { / Container / }
[data-authos-field="email"] { / Email field wrapper / }
[data-authos-field="password"] { / Password field wrapper / }
[data-authos-submit] { / Submit button / }
[data-authos-error] { / Error message / }
[data-authos-oauth] { / OAuth button / }
[data-authos-oauth][data-provider="github"] { / GitHub button / }
[data-authos-divider] { / "or" divider / }
[data-authos-magic-link] { / Magic Link container / }
[data-authos-passkey] { / Passkey container / }
`Security Considerations
$3
The SDK offers multiple storage options:
| Storage | Environment | Security Notes |
|---------|-------------|----------------|
|
BrowserStorage | Client-side | Uses localStorage, accessible to JS |
| CookieStorage | SSR (Next.js) | Non-httpOnly cookies, accessible to JS |
| MemoryStorage | SSR/Testing | In-memory, lost on page refresh |> [!WARNING]
>
CookieStorage and BrowserStorage store tokens accessible to JavaScript.
> For maximum security in production, consider:
> - Using httpOnly cookies set by your backend
> - Implementing a Backend-for-Frontend (BFF) pattern
> - Ensuring proper CSP headers to mitigate XSS$3
The Next.js middleware and Node adapter provide independent JWT verification:
- Next.js middleware: Uses Web Crypto API (
crypto.subtle) for Edge Runtime
- Node adapter: Uses Node.js crypto` moduleThis duplication is intentional due to runtime differences. Both implementations
verify signatures using your JWKS endpoint.
MIT © DRM HSE