Cookie based auth with Convex
@danielo515 asked:
Hello. I have an astro site hosted on Vercel. I have auth using cookies . If I want to use some convex database, what will be my best bet? I assume that I can use some "admin token" in the backend for basic crud operations after checking user permissions, and also have an endpoint to issue tokens to the clients to read from the real-time database. Does that make sense?
10 Replies
My best answer is pass a short-lived session ID to your functions. You can follow this example:
https://stack.convex.dev/convex-with-lucia
In this example the Convex backend is the authentication authority. If you want your astro server to be the authentication authority, you can implement the OpenID protocol on it, but this is more involved.
Custom Authentication (with Lucia)
Learn how to build a full stack app with authentication without any third-party auth providers, using Convex and the Lucia library.
I saw that example, thank you. I decided to use my astro backend for the auth because they provide a very simple postgres implementation that Lucia has very simple integration
If I use convex as my authentication authority, my astro backend will have no idea of the session when it is time to render the dynamic pages
So I will also need to issue their own cookie validating a token with the convex backend or something like that, same situation but reversed . Right?
What do you mean, to my functions? When the frontend calls the Astro backend ? Does convex client automatically fetches such tokens ? Or I will have to implement such lotic on my FE?
Yeah, you have to pass the session ID from the Astro server to your client, pass it from your client through your functions to your Convex, and then validate in Convex.
Aren't "my functions" already on convex side ?
Taking a step back, how do you call your Convex functions?
Right now I don't 😅
The plan was to get a token from my backend, then from the frontend subscribe to database updates in read only mode. Adding data to the database will go throug the current backend as proxy
Yes. So:
1. Authenticate in Astro server
2. Get a short-lived session ID from Convex
3. Pass short-lived session ID to client
4. Call your Convex functions with the short lived session ID from the client
5. Validate the short lived session ID inside your Convex function
That sounds exactly like the flow that I have in mind thanks. Does convex have any already implemented method for the session id generation/validation or should I implement it myself?
There is some discussion of how to do this here: https://stack.convex.dev/track-sessions-without-cookies
Track Sessions Without Cookies
Advice and resources for session tracking per-tab or per-browser via localStorage / sessionStorage using React Context, hooks, and some utilities to m...
Awesome thanks