Possible race condition when sharing Supabase client across users

Say I have something like this as a request handler of my server:
async def get_session_middleware(request: web.Request):
# Get tokens from cookies
await supabase.auth.set_session(access_token, refresh_token)
user = await supabase.auth.get_user()
return user
async def get_session_middleware(request: web.Request):
# Get tokens from cookies
await supabase.auth.set_session(access_token, refresh_token)
user = await supabase.auth.get_user()
return user
If two users send a request at the same time, is there a chance that one of them will get logged in as another user? What is a better way of handling this?
4 Replies
ihm40
ihm402mo ago
maybe creating clients per request?
gldanoob
gldanoobOP5w ago
wouldn't the overhead be huge?
Ninjeneer
Ninjeneer5w ago
I'd say on the server you should not log as the user. This is what the service role key is for, acting as admin on a server side You init only one supabase client, with your servicole key access, and you use it to do everything you need server side
vick
vick4w ago
Looks like python code. I'm more familar with typescript. The answer really depends on how python isolates the function call stack. In javascript/typescript, if you store the supabase client as a global variable, it will be shared across all running functions and you will suffer the cross-authentication problems. The way around this is to execute your code inside of an async context and isolating any shared variables inside of it so each "thread" sees its own copy of the variables.

Did you find this page helpful?