SvelteKit 集成
在开始之前,请确保你已配置了 Better Auth 实例。如果还没有配置,请查看安装指南。
【Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.】
安装处理程序
【Mount the handler】
我们需要将处理程序挂载到 SvelteKit 服务器钩子上。
【We need to mount the handler to SvelteKit server hook.】
import { auth } from "$lib/auth";
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from "$app/environment";
export async function handle({ event, resolve }) {
return svelteKitHandler({ event, resolve, auth, building });
}在事件中填充会话数据(event.locals)
【Populate session data in the event (event.locals)】
svelteKitHandler 不会自动填充 event.locals.user 或 event.locals.session。如果你想在服务器代码中访问当前会话(例如,在 +layout.server.ts、操作或端点中),请在你的 handle 钩子中填充 event.locals:
【The svelteKitHandler does not automatically populate event.locals.user or event.locals.session. If you want to access the current session in your server code (e.g., in +layout.server.ts, actions, or endpoints), populate event.locals in your handle hook:】
import { auth } from "$lib/auth";
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from "$app/environment";
export async function handle({ event, resolve }) {
// Fetch current session from Better Auth
const session = await auth.api.getSession({
headers: event.request.headers,
});
// Make session and user available on server
if (session) {
event.locals.session = session.session;
event.locals.user = session.user;
}
return svelteKitHandler({ event, resolve, auth, building });
}服务器操作 Cookie
【Server Action Cookies】
为了确保在调用如 signInEmail 或 signUpEmail 这样的服务器操作函数时,cookie 能够正确设置,你应该使用 sveltekitCookies 插件。这个插件会在 SvelteKit 中自动帮你处理 cookie 的设置。
【To ensure cookies are properly set when you call functions like signInEmail or signUpEmail in a server action, you should use the sveltekitCookies plugin. This plugin will automatically handle setting cookies for you in SvelteKit.】
你需要将其作为插件添加到你的 Better Auth 实例中。
【You need to add it as a plugin to your Better Auth instance.】
getRequestEvent 函数在 SvelteKit 2.20.0 及更高版本可用。
请确保你使用的是兼容的版本。
import { betterAuth } from "better-auth";
import { sveltekitCookies } from "better-auth/svelte-kit";
import { getRequestEvent } from "$app/server";
export const auth = betterAuth({
// ... your config
plugins: [sveltekitCookies(getRequestEvent)], // make sure this is the last plugin in the array
});创建客户端
【Create a client】
创建一个客户端实例。你可以随意命名文件。在这里,我们在 lib/ 目录下创建 client.ts 文件。
【Create a client instance. You can name the file anything you want. Here we are creating client.ts file inside the lib/ directory.】
import { createAuthClient } from "better-auth/svelte"; // make sure to import from better-auth/svelte
export const authClient = createAuthClient({
// you can pass client configuration here
});一旦创建了客户端,你就可以使用它进行注册、登录以及执行其他操作。一些操作是响应式的。客户端使用 nano-store 来存储状态,并在发生变化时反映变化,例如用户登录或登出会影响会话状态。
【Once you have created the client, you can use it to sign up, sign in, and perform other actions. Some of the actions are reactive. The client use nano-store to store the state and reflect changes when there is a change like a user signing in or out affecting the session state.】
示例用法
【Example usage】
<script lang="ts">
import { authClient } from "$lib/client";
const session = authClient.useSession();
</script>
<div>
{#if $session.data}
<div>
<p>
{$session.data.user.name}
</p>
<button
on:click={async () => {
await authClient.signOut();
}}
>
Sign Out
</button>
</div>
{:else}
<button
on:click={async () => {
await authClient.signIn.social({
provider: "github",
});
}}
>
Continue with GitHub
</button>
{/if}
</div>