Users getting "permission denied" with anon JWT when authenticated session should still be valid
Hey folks! Running into a puzzling auth issue with @supabase/ssr in Next.js and could use some help diagnosing it.
Setup: - Next.js 14 with @supabase/ssr (server-side auth with cookies) - Access token expiry: 1 hour - Refresh token rotation: enabled - No session expiration - Middleware refreshes session on page navigation via supabase.auth.getUser()
The Problem: Occasionally, users get "permission denied" errors when trying to query the DB. Database logs show the request is being made with the anon JWT instead of their authenticated session token. As we have RLS-policies requiring the user to be authenticated, the "permission denied" error is expected given that the user has no access token (I think).
What's confusing: Why does the user no longer have a valid access token? Could it be that the token rotation failed, never happened, or something else?
Questions: 1. When using @supabase/ssr with Next.js middleware, does the client-side Supabase instance automatically refresh tokens when they expire? Only active tabs? It seems like this happens more frequently in my PWA running in standalone mode on mobile devices. 2. Ideally, the user should never loose their access token if not actively logging out. But if they do, what's the recommended way to detect this client-side and redirect to login?
Supabase gives you the tools, documentation, and community that makes managing databases, authentication, and backend infrastructure a lot less overwhelming.