-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
SvelteKitAuth: How to update session from client to server and vice versa #9147
Comments
Seems like it's not implemented. |
Okey, it's actually supported, you can use next function: import { base } from '$app/paths';
import type { Session } from '@auth/core/types';
export async function updateSession(data: Session): Promise<Session | null> {
const sessionUrl = `${base}/auth/session`;
const csrfTokenResponse = await fetch(`${base}/auth/csrf`);
const { csrfToken } = await csrfTokenResponse.json();
const res = await fetch(sessionUrl, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data,
csrfToken,
}),
});
const json = await res.json();
return json;
} also you should extend JWT callback in SvelteKitAuth options: async jwt({
token,
user,
session,
trigger,
}: {
token: JWT,
user: SessionUser,
session?: Session,
trigger?: string | undefined,
}) {
if (trigger === 'signIn' && user) {
Object.assign(token, { user });
} else if (trigger === 'update') {
Object.assign(token, { user: session?.user });
}
return token;
}, it's should cover |
@aakash14goplani it's working fine for me, I can update session user and it's keeps during browser restart. |
The PR #9497 is more about run getSession or set session from the SSR, if you will run my function from the client it will not a case. |
@aakash14goplani this function can return also return { json, cookie: res.headers.getSetCookie() }; something like this, after in your SSR function you can just set a such cookies. |
After recent changes made in SvelteKitAuth v0.10 and v0.11, I am using following approach for to-and-fro communication. Client to ServerGeneral Idea: Update data by making API call
Server to ClientGeneral Idea: Update data using hydration
This is the long route that I have to implement in SvelteKit as there are no helper methods exposed by SvelteKitAuth (when compared with NextAuth). So @balazsorban44 @ThangHuuVu and @ndom91 can you please go through this approach and let me know if this is correct way (for now) or something could be improved? Example Repo: https://github.com/aakash14goplani/sveltekit-auth-session-token/tree/new-version-test |
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
This comment was marked as off-topic.
@benevbright - Glad that you're able to find the solution but you posted in a wrong thread. This thread is meant for the "SvelteKit" framework and not "Next" framework! |
@aakash14goplani you're right. I hid my comments as off topic. 🙏 |
comment by @stalkerg works for me. I am doing the complete registration when I need the user to fill the profile after registration. here is my code. export const actions: Actions = {
/**
*
* @param {RequestEvent} event sveltekit request event
* @returns
*/
complete: async (event: RequestEvent) => {
const form = await superValidate(event.request, zod(schema));
const session = (await event.locals.auth()) as QuantmAdapterSession;
if (!form.valid) {
return fail(400, { form });
}
const name = form.data.name;
const getopts = { method: 'GET' };
const postopts = { method: 'POST' };
const headers = { 'Content-Type': 'application/json' };
const refresh = async (team: Team) =>
event
// get authjs crsf token
.fetch(`${base}/auth/csrf`, { ...getopts })
.then(response => response.json())
// assign user to team
.then(csrf => {
// @ts-expect-error we know there will be user.
session.user.team_id = team.id;
return JSON.stringify({ data: session, ...csrf });
})
// update token with updated user
.then(body => event.fetch(`${base}/auth/session`, { ...postopts, headers, body }))
.then(response => response.json())
.then(() => ({ form, team }));
return api().auth.createTeam({ name }).then(refresh);
},
}; |
I haven't read through all of the posts in this thread, but there is an So for implementing this in SvelteKit + Auth.js projects, maybe its helpful to look at that next-auth implementation. Yall can find it here: https://github.com/nextauthjs/next-auth/blob/main/packages/next-auth/src/lib/actions.ts#L110-L133 |
Found the solution (at least for now) https://blog.aakashgoplani.in/how-to-exchange-data-between-client-and-server-using-sveltekitauth |
What is the improvement or update you wish to see?
Scenario 1: Client to Server
In SvelteKitAuth, how to communicate session updates from client to server?
In NextAuth, we do something like:
Scenario 2: Server to Client
In SvelteKitAuth, we manage session within
jwt({ ... })
andsession({ ... })
callbacks. Let's consider a scenario in which user object was mutated by some event (like response from API call), how to update global session object in that case?Is there any context that might help us understand?
The NextAuth has many helper methods exposed for both Client and Server API that makes it easy t implement above mentioned scenarios. How do we implement those in SvelteKitAuth?
Does the docs page already exist? Please link to it.
https://next-auth.js.org/getting-started/client#updating-the-session
The text was updated successfully, but these errors were encountered: