RequireAuth
RequireAuth is a guard component that ensures its children are only rendered when the user is authenticated. It handles token expiry and automatic refresh.
Installation
Section titled “Installation”npm install oidc-js-svelte<script lang="ts"> import { RequireAuth } from "oidc-js-svelte";</script>
<RequireAuth> {#snippet children()} <h1>Protected Content</h1> {/snippet} {#snippet fallback()} <p>Loading...</p> {/snippet}</RequireAuth>| Prop | Type | Default | Description |
|---|---|---|---|
children | Snippet | required | Content to render when authenticated |
fallback | Snippet | - | Shown while loading or redirecting |
autoRefresh | boolean | true | Auto-refresh expired tokens before redirecting to login |
loginOptions | LoginOptions | - | Options passed to actions.login() when redirecting |
Behavior
Section titled “Behavior”When RequireAuth renders:
- If still loading (discovery, callback), render
fallback - If authenticated with a valid token, render
children - If the token is expired and
autoRefreshistrue, attempt a silent refresh - If refresh succeeds, render
childrenwith the new token - If refresh fails (or no refresh token), redirect to the IdP login
With SvelteKit
Section titled “With SvelteKit”<!-- src/routes/dashboard/+page.svelte --><script lang="ts"> import { RequireAuth } from "oidc-js-svelte";</script>
<RequireAuth> {#snippet children()} <h1>Dashboard</h1> <p>This content is only visible when authenticated.</p> {/snippet} {#snippet fallback()} <p>Checking authentication...</p> {/snippet}</RequireAuth>