markjaquith / clerk-sveltekit

Clerk adapter for SvelteKit
Other
146 stars 21 forks source link

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

Open nicolasmendonca opened 9 months ago

nicolasmendonca commented 9 months ago

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 commented 9 months ago

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