Skip to content

getAuthContext

getAuthContext retrieves the reactive authentication context from the nearest AuthProvider ancestor. It must be called during component initialization (not inside event handlers or async callbacks).

Terminal window
npm install oidc-js-svelte
<script lang="ts">
import { getAuthContext } from "oidc-js-svelte";
const auth = getAuthContext();
</script>
{#if auth.isLoading}
<p>Loading...</p>
{:else if auth.error}
<p>Error: {auth.error.message}</p>
{:else if auth.isAuthenticated}
<p>Hello, {auth.user?.claims.sub}</p>
<button onclick={() => auth.actions.logout()}>Log out</button>
{:else}
<button onclick={() => auth.actions.login()}>Log in</button>
{/if}

All properties on the returned object are reactive getters powered by Svelte 5 runes. They update automatically when the authentication state changes.

PropertyTypeDescription
configOidcConfigThe OIDC configuration
userAuthUser | nullThe authenticated user (claims + profile)
isAuthenticatedbooleanWhether the user is logged in
isLoadingbooleanWhether initialization is in progress
errorError | nullThe most recent auth error
tokensAuthTokensCurrent access, id, and refresh tokens
actionsAuthActionsMethods for login, logout, refresh, fetchProfile
ActionDescription
login(options?)Redirect to IdP login. Options: returnTo, extraParams
logout()Clear state and redirect to IdP logout endpoint
refresh()Exchange refresh token for new tokens
fetchProfile()Fetch the UserInfo endpoint and update user.profile