> ## Documentation Index
> Fetch the complete documentation index at: https://docs.timeback.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SvelteKit

> Integrate Timeback with SvelteKit

## Overview

The Timeback SDK provides a SvelteKit adapter using hooks.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @timeback/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @timeback/sdk
  ```

  ```bash yarn theme={null}
  yarn add @timeback/sdk
  ```

  ```bash bun theme={null}
  bun add @timeback/sdk
  ```
</CodeGroup>

## Server Setup

Create a Timeback instance:

```typescript src/lib/timeback.ts theme={null}
import { createTimeback } from '@timeback/sdk'

export const timeback = await createTimeback({
	env: 'staging',
	api: {
		clientId: process.env.TIMEBACK_API_CLIENT_ID!,
		clientSecret: process.env.TIMEBACK_API_CLIENT_SECRET!,
	},
	identity: {
		mode: 'sso',
		clientId: process.env.AWS_COGNITO_CLIENT_ID!,
		clientSecret: process.env.AWS_COGNITO_CLIENT_SECRET!,
		redirectUri: 'http://localhost:3000/api/timeback/identity/callback',
		onCallbackSuccess: async ({ user, state, redirect }) => {
			await setSession({ id: user.id, email: user.email })
			return redirect(state?.returnTo ?? '/')
		},
		onCallbackError: ({ error, redirect }) => {
			return redirect('/?error=sso_failed')
		},
		getUser: () => getSession(),
	},
})
```

## Server Hooks

Add the Timeback handler to your hooks:

```typescript src/hooks.server.ts theme={null}
import { svelteKitHandler } from '@timeback/sdk/svelte-kit'
import { building } from '$app/environment'
import { timeback } from '$lib/timeback'

import type { Handle } from '@sveltejs/kit'

export const handle: Handle = ({ event, resolve }) => {
	return svelteKitHandler({
		timeback,
		event,
		resolve,
		building,
	})
}
```

## Alternative: Route-Based Handler

For more control, you can use a route-based approach instead of hooks:

```typescript src/routes/api/timeback/[...path]/+server.ts theme={null}
import { toSvelteKitHandler } from '@timeback/sdk/svelte-kit'
import { timeback } from '$lib/timeback'

const handlers = toSvelteKitHandler(timeback)

export const GET = handlers.GET
export const POST = handlers.POST
```

## Client Setup

Initialize Timeback in your root layout:

```svelte src/routes/+layout.svelte theme={null}
<script>
  import { initTimeback } from '@timeback/sdk/svelte'

  initTimeback()

  let { children } = $props()
</script>

{@render children()}
```

## Usage

<Tip>
  For the full client-side API, see the [Svelte client
  adapter](/beta/build-on-timeback/sdk/client/svelte).
</Tip>

Use stores in components:

```svelte src/routes/+page.svelte theme={null}
<script>
  import { onMount, onDestroy } from 'svelte'
  import { SignInButton, timeback } from '@timeback/sdk/svelte'

  let activity

  onMount(() => {
    if ($timeback) {
      activity = $timeback.activity.start({
        id: 'lesson-1',
        name: 'Introduction',
        course: { subject: 'Math', grade: 3 },
      })
    }
  })

  onDestroy(() => activity?.end())
</script>

{#if !$timeback}
  <SignInButton size="lg">Sign In</SignInButton>
{:else}
  <div>Welcome!</div>
{/if}
```

## Profile Store

```svelte theme={null}
<script>
  import {
    timebackProfile,
    timebackProfileCanFetch,
    fetchTimebackProfile
  } from '@timeback/sdk/svelte'
</script>

<button onclick={fetchTimebackProfile} disabled={!$timebackProfileCanFetch}>
  {$timebackProfile.status === 'loading' ? 'Loading...' : 'Load Profile'}
</button>

{#if $timebackProfile.status === 'loaded'}
  <div>XP: {$timebackProfile.profile.xp.today}</div>
{/if}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Svelte Client" href="/beta/build-on-timeback/sdk/client/svelte">
    Client-side Svelte integration
  </Card>

  <Card title="Identity" href="/beta/build-on-timeback/sdk/identity">
    Authentication options
  </Card>

  <Card title="Custom Activities" href="/beta/build-on-timeback/sdk/activity-tracking/intro">
    Track learning sessions
  </Card>
</CardGroup>
