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
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
and how would you do that?
because the pages come as children to the root layout right?
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
i guess you could apply a layout to each page just to add the protected route on the outside
https://medium.com/@turingvang/nextjs-middleware-protected-routes-bcb3df06db0c this looks recent enough, would it help?
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…
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
which part of supabase are you looking at
if you look at the docs on the nextjs guide at number 4 there are 2 middleware files
ahh right to answer your original question it seems like
supabase.auth.getUser
is the reccomended approach for next.js at leastso i do have to use it in every page
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.
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
no worries, wish i could help more
You can refer to this example app
https://github.com/silentworks/supabase-by-example/tree/main/nextjs