Generic OAuth SSO (server side) in sveltekit

Having a hard time udnerstanding how to implement the SSO eredirect server side. This only explains how to use it client side: https://www.better-auth.com/docs/plugins/generic-oauth What I have now is this:
# hooks.server.ts

import { auth, checkSession } from "$lib/server/auth";
import { type Handle } from "@sveltejs/kit";
import { sequence } from "@sveltejs/kit/hooks";
import { svelteKitHandler } from "better-auth/svelte-kit";

const handleAuth: Handle = async ({ event, resolve }) => {
return svelteKitHandler({ event, resolve, auth });
};

export const handleRouting: Handle = async ({
event,
resolve
}) => {
const session = await checkSession(event);
if (!session) await auth.api.signInWithOAuth2({ body: { providerId: "example-provider-id", callbackURL: "https://localhost:5173" } })
return resolve(event);
};


export const handle: Handle = sequence(
handleAuth,
handleRouting
);
# hooks.server.ts

import { auth, checkSession } from "$lib/server/auth";
import { type Handle } from "@sveltejs/kit";
import { sequence } from "@sveltejs/kit/hooks";
import { svelteKitHandler } from "better-auth/svelte-kit";

const handleAuth: Handle = async ({ event, resolve }) => {
return svelteKitHandler({ event, resolve, auth });
};

export const handleRouting: Handle = async ({
event,
resolve
}) => {
const session = await checkSession(event);
if (!session) await auth.api.signInWithOAuth2({ body: { providerId: "example-provider-id", callbackURL: "https://localhost:5173" } })
return resolve(event);
};


export const handle: Handle = sequence(
handleAuth,
handleRouting
);
And auth
auth.ts

import type { RequestEvent } from "@sveltejs/kit";
import { betterAuth } from "better-auth"
import { genericOAuth } from "better-auth/plugins"

export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
{
providerId: "example-provider-id",
clientId: "---",
clientSecret: "---",
discoveryUrl: "---",
},
]
})
]
})

export async function checkSession(e: RequestEvent) {
const session = await auth.api.getSession({
headers: e.request.headers
});
return session;
}
auth.ts

import type { RequestEvent } from "@sveltejs/kit";
import { betterAuth } from "better-auth"
import { genericOAuth } from "better-auth/plugins"

export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
{
providerId: "example-provider-id",
clientId: "---",
clientSecret: "---",
discoveryUrl: "---",
},
]
})
]
})

export async function checkSession(e: RequestEvent) {
const session = await auth.api.getSession({
headers: e.request.headers
});
return session;
}
in hooks, I expect to be redirected to the OAuth signin (whatever it is) but it doesn't seem to work like that. I can find very little documentation about how this is supposed to be implemented. Any help or nudge in the right direction would be appreciated!
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?