Files
better-auth/docs/content/docs/integrations/svelte-kit.mdx
Bereket Engida 98402835c2 feat: Database adapters (#29)
* feat: prisma adapter

* feat: drizzle adapter

* feat: mongod db adapter
2024-09-29 20:00:47 +03:00

99 lines
2.4 KiB
Plaintext

---
title: Svelte Kit Integration
description: Learn how to integrate Better Auth with Svelte Kit
---
Before you start, make sure you have a better auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
### Mount the handler
We need to mount the handler to svelte kit server hook.
```ts
import { auth } from "$lib/auth";
import { svelteKitHandler } from "better-auth/svelte-kit";
export async function handle({ event, resolve }) {
return svelteKitHandler({ event, resolve, auth });
}
```
### Migrate the database
Run the following command to create the necessary tables in your database:
```bash
npx better-auth migrate
```
## Create a client
Create a client instance. You can name the file anything you want. Here we are creating `client.ts` file inside the `lib/` directory.
```ts twoslash title="client.ts"
import { createAuthClient } from "better-auth/svelte" // make sure to import from better-auth/svlete
export const client = createAuthClient({
//you can pass client configuration here
})
```
Once you have created the client, you can use it to sign up, sign in, and perform other actions.
Some of the actinos are reactive. The client use [nano-store](https://github.com/nanostores/nanostores) to store the state and refelct changes when there is a change like a user signing in or out affecting the session state.
### Example usage
```svelte
<script lang="ts">
import { client } from "$lib/client";
const session = client.$session;
</script>
<div>
{#if $session}
<div>
<p>
{$session?.user.name}
</p>
<button
on:click={async () => {
await client.signOut();
}}
>
Signout
</button>
</div>
{:else}
<button
on:click={async () => {
await client.signIn.social({
provider: "github",
});
}}
>
Continue with github
</button>
{/if}
</div>
```
### Example: Getting Session on a loader
```ts title="+page.ts"
import { auth } from "$lib/auth";
export async function load(request: Request) {
const session = await auth.api.getSession({
headers: request.headers,
});
if (!session) {
return {
status: 401,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
error: "Unauthorized",
}),
};
}
return session;
}
```