Unclear on how to handle session and cookies in sveltekit

I've followed the sveltekit guide from better auth website However i think it is unclear on how to do sveltekit auth on server side, on the example you do so by doing it on the client but normally you would do a login +page.svelte and then a +page.server.svelte and there you would call the auth.api.signInSocial (or email). Example:
// auth/login/+page.server.ts

export const actions: Actions = {
login: async (event) => {
let provider = event.url.searchParams.get("provider")
const form = await superValidate(event, zod(loginSchema));
let redirectUrl = "";
if (provider) {
try {
console.log("provider", provider);
let data = await auth.api.signInSocial({
body: {
provider: provider,
callbackURL: "http://localhost:5174",
},
headers: event.request.headers,
});
redirectUrl = data.url!;
} catch (error) {
if (error instanceof APIError) {
redirectUrl = "/login";
if (provider) {
return fail(400, {
message: "Something went wrong with social login",
});
} else {
setError(form, "email", "Invalid Credentials");
setError(form, "password", "Invalid Credentials");
return fail(400, { form });
}
}
}
}

throw redirect(302, redirectUrl);
},
};
// auth/login/+page.server.ts

export const actions: Actions = {
login: async (event) => {
let provider = event.url.searchParams.get("provider")
const form = await superValidate(event, zod(loginSchema));
let redirectUrl = "";
if (provider) {
try {
console.log("provider", provider);
let data = await auth.api.signInSocial({
body: {
provider: provider,
callbackURL: "http://localhost:5174",
},
headers: event.request.headers,
});
redirectUrl = data.url!;
} catch (error) {
if (error instanceof APIError) {
redirectUrl = "/login";
if (provider) {
return fail(400, {
message: "Something went wrong with social login",
});
} else {
setError(form, "email", "Invalid Credentials");
setError(form, "password", "Invalid Credentials");
return fail(400, { form });
}
}
}
}

throw redirect(302, redirectUrl);
},
};
continuing below due to discord's character limit
SvelteKit Integration | Better Auth
Integrate Better Auth with SvelteKit.
5 Replies
Omicrxn
OmicrxnOP5d ago
After doing so my session is still null on all server side and also in the +hooks.svelte.ts where i do an Auth Guard which doesn't get triggered as the session is null. I've seen similar issues and the answer is saying to set the cookies manually as server getSession() doesn't do that but despite knowing how to do it with event.cookies.set it's unclear how to get the auth cookie from better auth. Also i think a great idea would be that better auth handles this internally, for instance supabase does this like this:
const supabase: Handle = async ({ event, resolve }) => {
event.locals.supabase = createServerClient(
PUBLIC_SUPABASE_URL,
PUBLIC_SUPABASE_ANON_KEY,
{
cookies: {
getAll: () => event.cookies.getAll(),
/**
* SvelteKit's cookies API requires `path` to be explicitly set in
* the cookie options. Setting `path` to `/` replicates previous/
* standard behavior.
*/
setAll: (cookiesToSet) => {
cookiesToSet.forEach(({ name, value, options }) => {
event.cookies.set(name, value, { ...options, path: "/" });
});
},
},
},
);

return resolve(event, {
filterSerializedResponseHeaders(name) {
/**
* Supabase libraries use the `content-range` and `x-supabase-api-version`
* headers, so we need to tell SvelteKit to pass it through.
*/
return name === "content-range" || name === "x-supabase-api-version";
},
});
};
const supabase: Handle = async ({ event, resolve }) => {
event.locals.supabase = createServerClient(
PUBLIC_SUPABASE_URL,
PUBLIC_SUPABASE_ANON_KEY,
{
cookies: {
getAll: () => event.cookies.getAll(),
/**
* SvelteKit's cookies API requires `path` to be explicitly set in
* the cookie options. Setting `path` to `/` replicates previous/
* standard behavior.
*/
setAll: (cookiesToSet) => {
cookiesToSet.forEach(({ name, value, options }) => {
event.cookies.set(name, value, { ...options, path: "/" });
});
},
},
},
);

return resolve(event, {
filterSerializedResponseHeaders(name) {
/**
* Supabase libraries use the `content-range` and `x-supabase-api-version`
* headers, so we need to tell SvelteKit to pass it through.
*/
return name === "content-range" || name === "x-supabase-api-version";
},
});
};
overall my request is that the sveltekit docs get updated to a real world scenario and also something that actually works similar to supabase docs where you can see how to handle typical files such as +hooks.server.ts +layout.ts etc https://supabase.com/docs/guides/auth/server-side/sveltekit and also to know how cookies must be handled in sveltekit server
Omicrxn
OmicrxnOP5d ago
i think this issue proposes something similar to what supabase does: https://github.com/better-auth/better-auth/issues/2020
GitHub
Cookie caching doesn't renew in SvelteKit · Issue #2020 · better-...
Is this suited for github? Yes, this is suited for github To Reproduce Enable cookie caching in server-side for example for 30 seconds It creates session_data in browser and once it expires, it nev...
Omicrxn
OmicrxnOP5d ago
Thank you for the help in advanced! i've been trying multiple methods, even using the client Auth but no luck the session is always null, in server and in client, using getSession, useSession it doesn't matter, the database does have an access token so i guess the auth is completing successfully. Any insights?
Stuart B
Stuart B4d ago
I've just had a similar issue. Make sure that in +hooks.server.ts you exclude /api/auth/ from any redirect. Otherwise when the oAuth provider does it's callback, it just gets redirected back to the login page, rather than to the better-auth api. That wasted me 3 hours!
Omicrxn
OmicrxnOP4d ago
damm hate it when these silly mistakes take too long hahahah the life of a programmer, however it is not my scenario, I only have app/ route protected, api and others should be fine, thanks for the tip though, appreciate it!

Did you find this page helpful?