Next js + Supabase (Auth: Middleware + Context)
Answered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
Hey everyone, I’m working on a project with Next.js and Supabase. I use middleware to protect routes, validate roles, and refresh the token, and I also have an Auth Context to avoid calling .getUser() on every request or whenever I need user information. I realized I’m calling .getUser() twice: once in the middleware for its operations and again in the context to hydrate it. I suspect that’s not a good practice. How have you handled this in your projects when you’ve faced this situation?
Answered by Rainbow trout
You shouldn't just rely on middleware for authorization, always check at the page level (not layout!). Supabase is using JWT's so you're not hitting a database on each request anyways. Do basic checks inside your middleware and anything other than that at the page level.
2 Replies
Rainbow trout
You shouldn't just rely on middleware for authorization, always check at the page level (not layout!). Supabase is using JWT's so you're not hitting a database on each request anyways. Do basic checks inside your middleware and anything other than that at the page level.
Answer
@Rainbow trout You shouldn't just rely on middleware for authorization, always check at the page level (not layout!). Supabase is using JWT's so you're not hitting a database on each request anyways. Do basic checks inside your middleware and anything other than that at the page level.
Boerboel
Yes layout only runs at start so when you navigate to the same layout group it will not rerun thus it wont check. Best pratice is either doing it in page level, and try implemting a function for reusability. And normally for getUser i believe cache is also handled by supabse in the recent change.