SvelteKit Integration
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
We need to mount the handler to SvelteKit server hook.
Server Action Cookies
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.
You need to add it as a plugin to your Better Auth instance.
The getRequestEvent
function is available in SvelteKit 2.2.0
and later.
Make sure you are using a compatible version.
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.
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.