Skip to content
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

Adding server-side data when the session is set in the client #38

Open
nicolasmendonca opened this issue Dec 24, 2023 · 1 comment
Open

Comments

@nicolasmendonca
Copy link

Hi folks, thanks for creating this wonderful lib.

I just wanted to contribute with something that I've been struggling the last couple of days.

So the way that I'm using this package is I have the following code:

// hooks.server.ts
export const handle: Handle = sequence(
	await handleClerk(CLERK_SECRET_KEY, {
		debug: NODE_ENV === 'development',
		protectedPaths: ['/dashboard'],
		signInUrl: route('/login')
	}),
	async ({ event, resolve }) => {
		let repository = new UnauthenticatedPrismaRepository();
		if (event.locals.session?.userId) {
			const authUser = await repository.getUserByExternalId(event.locals.session?.userId);
			repository = new AuthenticatedPrismaRepository(authUser);
			event.locals.authUser = authUser; // ⚠️ I care about my own user model, not clerks data...
		}
		event.locals.repository = repository;

		return resolve(event);
	}
);
// +layout.server.ts
export const load: LayoutServerLoad = async ({ locals }) => {
	return {
		authUser: locals.authUser,
	};
};

And then in my "frontend-side" components I use the export let data: PageData method to grab the authUser and get the auth details from the server.

My problem was that after signing in and get redirected, the server won't have the cookie and the clerk user data, but the frontend will. And this lib doesn't expose a callback outside a svelte template that will allow my server to send this data after the authentication has happened.

But after diving into the code, I found that a custom event was being sent. So after putting this together all my problems were solved. So I thought of sharing this in case it helps someone else.

<!-- +layout.svelte -->
<script lang="ts">
	onMount(() => {
		const eventName = 'clerk-sveltekit:user' as const;
		const callback = () => {
			console.log('ℹ️ received clerk session - calling `invalidateAll`');
			invalidateAll();
		};
		document.addEventListener(eventName, callback);

		return () => {
			document.removeEventListener(eventName, callback);
		};
	});
</script>
@markjaquith
Copy link
Owner

I think you'll be able to implement this more simply once I fix #36!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants