Managing users across pages
Hi,
I'm fairly new to Supabase and Next JS, so hope someone can help.
I'm currently working on a next js web app where i'm using supabase for authentication. I've followed this guide: https://supabase.com/docs/guides/auth/server-side/creating-a-client?queryGroups=environment&environment=middleware and have seemingly gotten everything to work properly. However, i'm unsure about managing users across restricted pages, as the process seems a bit counter intuitive.
Specifically, I've setup:
- Middleware that awaits updateSession - a Supabase middleware fuction.
- authentication/callback/route that process a succesful log in for a user
- ServerClient
- BrowserClient
From my understanding, to fetch a users authentication status on a new page, i'll need to create the client and call supabase every page, like:
// Client
const supabase = createClient()
useEffect(() => {
const checkAuth = async () => {
const { data: { user }, error } = await supabase.auth.getUser()
if (error || !user) {
router.push("/auth/signup");
return;
}
setUser(user);
};
checkAuth();
}, [router, supabase.auth]);
//Server
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
console.log("chat/layout.tsx User Request");
if (!user) {
redirect("/auth/signup");
}
const supabase = createClient()
Besides seeming a bit redundant to call supabase so many times during a users session, it also seems a bit laggy (my UI renders before the useEffect finishes and thus any user details displayed are left as Undefined until the request finishes.
My biggest worry is that i see in my Supabase dashboard that a single user can end up calling the service hundreds of times during a session (if they move a lot around on the restricted pages) - this is particular bad during development, where an hour of coding leads to almost 1000s requests.
Am i doing it correct - is this supposed to be done this way?