Before we can begin to access authentication state, the Corbado.load()
call has to resolve.
Find more here.
One-time access to Authentication State
If you want to access user state once, you can simply call Corbado.sessionToken
,
Corbado.user
or Corbado.isAuthenticated
to get the current user state.
<script lang="ts">
import Corbado from '@corbado/web-js';
import { onMount } from 'svelte';
onMount(async () => {
const resp = await fetch("https://acme.com/api", {
headers: {
// access the users session token once
Authorization: `Bearer ${Corbado.sessionToken}`
}
})
// process result
});
</script>
<div>
</div>
Subscribing to Authentication State
If you want to synchronize user state to your own state, you can subscribe to the authStateChanges
and userChanges
observables.
<script lang="ts">
import Corbado from '@corbado/web-js';
import {isCorbadoLoaded} from "../corbadoStore";
import type {SessionUser} from "@corbado/types";
import {onDestroy} from "svelte";
import {Subscription} from "rxjs"
let loggedIn = false;
let user: SessionUser | undefined;
let authStateSubscription: Subscription;
let userSubscription: Subscription;
$: if ($isCorbadoLoaded) {
authStateSubscription = Corbado.authStateChanges.subscribe(
next => loggedIn = next === 1
);
userSubscription = Corbado.userChanges.subscribe(next => user = next);
}
onDestroy(() => {
authStateSubscription?.unsubscribe();
userSubscription?.unsubscribe();
});
</script>
<div>
{#if loggedIn}
<h1>Welcome, {user?.email}!</h1>
{:else}
<h1>Log in to see your profile</h1>
{/if}
</div>
Logout
You can log out the user by calling Corbado.logout
.
<script lang="ts">
import Corbado from '@corbado/web-js';
</script>
<button on:click={Corbado.logout}>
Logout
</button>
Next
Access user information on the server-side of your application.