Best way to manage user plan/tier (access token/app metadata/ DB queries)
Hi all,
I've been playing around with Supabase auth and I want to learn more about the pros/cons of different wats to manage user plan (FREE/PREMIUM). I researched around for the last few days but feel like it is still unanswered.
Requirements are:
- Secure storage: user can't edit it
- Enforce rules on operations: ensure user don't overstep their tier. For example, free users can only see 2 lists
- Efficient retrieval: without calling too many checks or refreshing tokens
- Good dev experience?: easy to implement and manage (i feel like this is optional since each things have their own struggles)
1 Reply
Methods I found:
- Custom claim with server: Thanks to Custom Access token hook, I can query table and set custom claim in the token.
- The only issue I have is how to use this token on server, it feels a bit clunky. Custom claim is only available in access token which can either be accessed through localstorage (if I do auth with browser client) or cookies (if we use server client)
- If the token is stored in the local storage, I can pass it to server using Auth Headers then validate it with
getUser
or jwtVerify if I don't need user info
- If I do auth in the backend, i will get the cookies, decode and then get the access code from there -> have to validate the access token too
- After validation, I can use access code for plan
- Custom claim with RLS: The recommended way on Supabase doc. With this you can utilise auth.jwt() -> 'plan'
in RLS policy which makes it more efficient. But RLS policies can be a bit tricky to manage since they are in the dashboard or you have to keep copies of your db migrations. Also if you want to use access code in your server, you have to do the above^
- App metadata: Set app metadata for user in auth.user. The only problem I have is the flow a bit (maybe im overthinking). When user signs up,
- if you use auth.signUp
api, you have to manually update the metadata as an admin but the session token is already created, it won't have your metadata until it is expired/refreshed. Unless you refresh your newly created token.
- if you auth.admin.createUser
with metadata, then you will have to sign user in again somehow (either auto sign them in or redirect them to login page again). I'm just afraid if you sign them in silently, what if one of the operations throws error, so it may require more care with this, unless you make them sign in again).
- DB query: I think this is the least favourable especially with user plan, which is unlikely to change often. It is inefficient to make an extra DB for role on every operation or whenever you need user role
sorry for tagging @garyaustin but I would really appreciate your opinion 💙 It looks like you are very active on GIthub and here with topics related to Auth