Protected routes
Guards and loaders for React Router: signed-out users go to sign-in and come back to where they were going.
Status: beta. Category: Auth.
import { RequireAuth, GuestOnly, RequireRole, AuthRevalidator, NEXT_PARAM } from '@glyphui/auth/react-router'
Exports: RequireAuth, GuestOnly, RequireRole, protectedLoader, guestLoader, useRedirectAfterSignIn, AuthRevalidator, useAuthRevalidation, NEXT_PARAM, safeRedirectPath, signInPathFor.
Notes
- The current path and query go into ?next=, and after sign-in useRedirectAfterSignIn (or GuestOnly) returns there.
- Only same-origin paths are followed: https://evil.com, //evil.com and javascript: in ?next= fall back to your default.
- RequireRole takes roles (any of several) and/or permission; give it a fallback or get a "no access" message.
- Guards render a spinner while the session loads; pass loading to change it.
- With loaders, render <AuthRevalidator /> once in your root route (or call useAuthRevalidation()): it re-runs loaders on sign-in and sign-out, so protectedLoader pages redirect after an idle or cross-tab sign-out.
- Requires react-router 7 or later.
RequireAuth props
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | The protected content. Default <Outlet />, so it works as a layout route. | |
loading | ReactNode | <LoadingState label="Checking your session…" className="min-h-48" /> | Shown while the session loads. |
redirectTo | string | /sign-in | Where signed-out users go. The current path is added as ?next=. Default /sign-in. |
Example: Role-gated content
RequireRole shows its fallback to users without the role. Switch users to see both.
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { RequireRole } from '@glyphui/auth/react-router'
import { Card, SegmentedControl, Text } from '@glyphui/ui'
const adapter = memoryAdapter({
latency: 0,
users: [
{ email: '[email protected]', password: 'pw', name: 'Admin', roles: ['admin'] },
{ email: '[email protected]', password: 'pw', name: 'Member', roles: ['member'] },
],
})
function AdminArea() {
const { user, signIn } = useAuth()
return (
<div className="grid w-full max-w-md gap-4">
<SegmentedControl
aria-label="Signed in as"
value={user?.email ?? ''}
onValueChange={(email) => signIn({ email, password: 'pw' })}
options={[
{ value: '[email protected]', label: 'Admin' },
{ value: '[email protected]', label: 'Member' },
]}
/>
{user && (
<RequireRole roles="admin">
<Card>
<Text weight="medium">Audit log</Text>
<Text size="small" tone="muted">
Only admins see this card.
</Text>
</Card>
</RequireRole>
)}
</div>
)
}
export default function Example() {
return (
<AuthProvider adapter={adapter} syncTabs={false}>
<AdminArea />
</AuthProvider>
)
}