[GH-ISSUE #230] Buggy setup with SvelteKit #8180

Closed
opened 2026-04-13 03:16:51 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @Vivillies on GitHub (Oct 18, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/230

Describe the bug
Going through the documentation and setting up better-auth with SvelteKit as provided prompts errors. Even when doing what better-call suggests (making sure the URL has the basePath "/api/auth") it only prompts errors.

To Reproduce
Steps to reproduce the behavior:
Follow the general setup and continue with the SvelteKit guide.

Expected behavior
Auth working.

Screenshots
image
image

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser Opera GX
  • Version 0.4.14-beta.2

Additional context
How I set it up:

// .env
BETTER_AUTH_SECRET="secret"
BETTER_AUTH_URL="http://localhost:5173"
BETTER_AUTH_TRUSTED_ORIGINS="http://localhost:5173" 
// $lib/auth.ts
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client } from "./database";
import { env } from "$env/dynamic/private";

export const auth = betterAuth({
      database: mongodbAdapter(client.db("test")),
      baseURL: "http://localhost:5173",
      basePath: "/api/auth",
      socialProviders: {
            google: {
                  clientId: env.GOOGLE_CLIENT_ID,
                  clientSecret: env.GOOGLE_SECRET_KEY
            }
      }
})
// $lib/auth-client.ts
import { createAuthClient } from "better-auth/svelte";

export const authClient = createAuthClient({
      baseURL: "http://localhost:5173"
})
// routes/+page.svelte
<script lang="ts">
      import { authClient } from "$lib/auth-client";
      const session = authClient.useSession();
</script>

<div>
      {#if $session.data}
            <div>
                  <p>
                        {$session?.data?.user.name}
                  </p>
                  <button
                        on:click={async () => {
                              await authClient.signOut();
                        }}
                  >
                        Signout
                  </button>
            </div>
      {:else}
            <button
                  on:click={async () => {
                        await authClient.signIn.social({
                              provider: "google",
                        });
                  }}
            >
                  Continue with google
            </button>
      {/if}
</div>
// routes/+page.server.ts (+page.ts doesn't actually work)
import { auth } from "$lib/auth";
import type { PageServerLoad } from "./$types";

export const load: PageServerLoad = async ({ 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;
}
// hooks.server.ts
import { auth } from "$lib/auth";
import { svelteKitHandler, } from "better-auth/svelte-kit";

export async function handle({ event, resolve }) {
      return svelteKitHandler({auth: auth, event: event, resolve: resolve})
}

I tried manually setting up an API endpoint for api/auth/[...auth] and disabling the hook (since they were colliding in some way). The library tried sending requests to http://localhost:5173/api/auth/csrf returning 405.

Originally created by @Vivillies on GitHub (Oct 18, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/230 **Describe the bug** Going through the documentation and setting up better-auth with SvelteKit as provided prompts errors. Even when doing what better-call suggests (making sure the URL has the basePath "/api/auth") it only prompts errors. **To Reproduce** Steps to reproduce the behavior: Follow the general setup and continue with the SvelteKit guide. **Expected behavior** Auth working. **Screenshots** ![image](https://github.com/user-attachments/assets/38e69821-8038-4064-ba17-07e5b048f711) ![image](https://github.com/user-attachments/assets/a54555b7-0f39-463f-ab4f-5e226387115c) **Desktop (please complete the following information):** - OS: Windows 10 - Browser Opera GX - Version 0.4.14-beta.2 **Additional context** How I set it up: ```.env // .env BETTER_AUTH_SECRET="secret" BETTER_AUTH_URL="http://localhost:5173" BETTER_AUTH_TRUSTED_ORIGINS="http://localhost:5173" ``` ```.ts // $lib/auth.ts import { betterAuth } from "better-auth"; import { mongodbAdapter } from "better-auth/adapters/mongodb"; import { client } from "./database"; import { env } from "$env/dynamic/private"; export const auth = betterAuth({ database: mongodbAdapter(client.db("test")), baseURL: "http://localhost:5173", basePath: "/api/auth", socialProviders: { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_SECRET_KEY } } }) ``` ```.ts // $lib/auth-client.ts import { createAuthClient } from "better-auth/svelte"; export const authClient = createAuthClient({ baseURL: "http://localhost:5173" }) ``` ```.svelte // routes/+page.svelte <script lang="ts"> import { authClient } from "$lib/auth-client"; const session = authClient.useSession(); </script> <div> {#if $session.data} <div> <p> {$session?.data?.user.name} </p> <button on:click={async () => { await authClient.signOut(); }} > Signout </button> </div> {:else} <button on:click={async () => { await authClient.signIn.social({ provider: "google", }); }} > Continue with google </button> {/if} </div> ``` ```.ts // routes/+page.server.ts (+page.ts doesn't actually work) import { auth } from "$lib/auth"; import type { PageServerLoad } from "./$types"; export const load: PageServerLoad = async ({ 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; } ``` ```.ts // hooks.server.ts import { auth } from "$lib/auth"; import { svelteKitHandler, } from "better-auth/svelte-kit"; export async function handle({ event, resolve }) { return svelteKitHandler({auth: auth, event: event, resolve: resolve}) } ``` I tried manually setting up an API endpoint for **api/auth/[...auth]** and disabling the hook (since they were colliding in some way). The library tried sending requests to `http://localhost:5173/api/auth/csrf` returning 405.
GiteaMirror added the locked label 2026-04-13 03:16:51 -05:00
Author
Owner

@Bekacru commented on GitHub (Oct 19, 2024):

Hopefully, this is fixed feel free to re-open if not.

<!-- gh-comment-id:2423721427 --> @Bekacru commented on GitHub (Oct 19, 2024): Hopefully, this is fixed feel free to re-open if not.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8180