S
Supabase2mo ago
axelis

Auth and protected pages

Hello guys i have a question, im currently building a saas project with nextjs , supabase .Im using the ssr client, middleware , server architecture to authenticate the user, and i am wondering if i need to use const supabase = await createClient(); const { data, error } = await supabase.auth.getUser(); if (error || !data?.user) { redirect("/login"); } in every page because even if i dont use it i cant access the pages since there is the redirect to login with middleware but is this safe? because i think it only checks for the session it doesnt actually check if the user is authenticated, also, if i want to hide my navbar if the user is not authenticated do i need to do the auth.getUser() again? wont that do 1 extra auth call in every page call?
15 Replies
ihm40
ihm402mo ago
Normally what people tend to do when they want to have a set of pages that only authenticated users can access is create a component that wraps around the pages and it authenticates the user before letting them access the page. Usually you only check for authenticated users for protected routes in that wrapper instead of for each page
axelis
axelisOP2mo ago
and how would you do that? because the pages come as children to the root layout right?
ihm40
ihm402mo ago
i think what you will need is a wraper around the routes that takes as children those routes that need authentication. I think if you search nextjs protected route wrapper you should find a fair view guides or videos
axelis
axelisOP2mo ago
i guess you could apply a layout to each page just to add the protected route on the outside
ihm40
ihm402mo ago
Medium
Nextjs Middleware Protected Routes
In Next.js, middleware for protected routes is a powerful feature used to enforce security on certain pages or routes. It ensures that only…
axelis
axelisOP2mo ago
yes thank you very much so i guess since supabase already does something like this in the middleware.js you dont have to "redo" it
ihm40
ihm402mo ago
which part of supabase are you looking at
axelis
axelisOP2mo ago
if you look at the docs on the nextjs guide at number 4 there are 2 middleware files
ihm40
ihm402mo ago
ahh right to answer your original question it seems like supabase.auth.getUser is the reccomended approach for next.js at least
axelis
axelisOP2mo ago
so i do have to use it in every page
ihm40
ihm402mo ago
i think it depends on your application, by the looks of it you can use the middleware.ts and the matches to specify routes to exclude i.e landing page but i've never used nextjs with supabase so i honestly can't be certain.
axelis
axelisOP2mo ago
hmm okay ill wait to see if anyone else can also answer so i can be sure thank you very much for your input though
ihm40
ihm402mo ago
no worries, wish i could help more

Did you find this page helpful?