Client-side Helpers
useClerkContext()
The Svelte SDK provides a useClerkContext() function that gives you access to the Clerk object, User object, Organization object, and a set of useful helper methods for signing in and signing up. They all leverage the power of Svelte Runes.
The useClerkContext() function returns the following properties:
auth- Access to the current user's authentication state and methods to manage the active session.user- TheUserobject.organization- TheOrganizationobject.session- TheSessionobject.clerk- TheClerkobject.
The following example demonstrates how to use the auth object to access the current auth state, like whether the user is signed in or not. It also demonstrates a basic example of how you could use the getToken() method to retrieve a session token for fetching data from an external resource.
<script lang="ts">
import { useClerkContext } from 'svelte-clerk/client';
// Do not destructure context to avoid losing reactivity
const ctx = useClerkContext();
const userId = $derived(ctx.auth.userId);
const fetchDataFromExternalResource = async () => {
const token = await ctx.session.getToken();
const response = await fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${token}`
}
});
return response.json();
};
</script>
{#if userId === undefined}
<p>Loading...</p>
{:else if userId === null}
<p>Sign in to view this page</p>
{:else}
<div>User ID: {userId}</div>
{/if}useSignIn()
The useSignIn() hook gives you access to the SignIn object for managing sign-in flows. You can use this to create a custom sign-in flow.
Returns:
signIn- TheSignInobject for the current sign-in attempt.errors- Structured errors from the last sign-in operation, with per-field errors (identifier,password,code) and global errors.fetchStatus-'idle'or'fetching', indicating whether a request is in flight.
<script lang="ts">
import { useSignIn } from 'svelte-clerk/client';
// Do not destructure to avoid losing reactivity
const signInState = useSignIn();
</script>
{#if signInState.signIn}
<p>Current sign-in status: {signInState.signIn.status}</p>
{/if}useSignUp()
The useSignUp() hook gives you access to the SignUp object for managing sign-up flows. You can use this to create a custom sign-up flow.
Returns:
signUp- TheSignUpobject for the current sign-up attempt.errors- Structured errors from the last sign-up operation, with per-field errors (firstName,lastName,emailAddress,phoneNumber,password,username,code,captcha,legalAccepted) and global errors.fetchStatus-'idle'or'fetching', indicating whether a request is in flight.
<script lang="ts">
import { useSignUp } from 'svelte-clerk/client';
// Do not destructure to avoid losing reactivity
const signUpState = useSignUp();
</script>
{#if signUpState.signUp}
<p>Current sign-up status: {signUpState.signUp.status}</p>
{/if}