EMILIANOME
Convex Community15mo ago
4 replies
EMILIANOM

Clerk, Convex and Svelte

Hey

I have successfully added clerk to my svelte project and I'm almost there with convex auth but I'm still missing something.

+layout.svelte
<script lang="ts">
    import type { LayoutData } from './$types';
    import { useClerkContext } from 'svelte-clerk';
    import { convexClient } from '$lib/convexClient';
    import { onMount, type Snippet } from 'svelte';

    // Do not destructure context or you'll lose reactivity!
    const ctx = useClerkContext();
    const session = $derived(ctx.session);

    async function getAuthToken() {
        const token = await session?.getToken({ template: 'convex' });
        console.log('token: ', token);
        return token;
    }

    $effect(() => {
        if (session) {
            convexClient.setAuth(getAuthToken);
        }
    });
    let { children, data }: { children: Snippet; data: LayoutData } = $props();
</script>

{@render children()}


<script lang="ts">
    import { useQuery } from 'convex-svelte';
    import { api } from '../../convex/_generated/api';
    import { convexClient } from '$lib/convexClient';

    // This doesn't work since I'm not using the convexClient instance, which has the auth function set
    const query = useQuery(api.tasks.get, {});
    // user: null

    // This works since I'm using the convexClient instance, which has the auth function set
    convexClient.query(api.tasks.get, {}).then((tasks) => console.log(tasks));
    // user: { id: '...', email: '...', ... }
</script>


is it possible to pass a custom convexClient to svelte useQuery?

** In react clerk you use "ConvexProviderWithClerk" (https://docs.convex.dev/api/modules/react_clerk)
I tried to reimplement it but it's just too time consuming since i don't know react and i don't fully understand the whole context.

Thanks, i really like convex but it's a bit of a pain working with it on svelte 5, i understand you are focused on react because its more adopted by the community 😦
React login component for use with Clerk.
Module: react-clerk | Convex Developer Hub
Was this page helpful?