Best practice around authentication checks in nested routes #12510
Unanswered
discoverlance-com
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am working on an application that requires authentication. I am using the cookie session storage to store the auth cookie with secrets.
In my authenticated pages and layouts, I am using a
requireUser
function in my loader to verify or require an authenticated user session which validates the session cookie and also retrieves the user information from the database so I can do something likeconst user = await requireUser(request)
when I need to access the logged in user details and also do auth checks.My main concerns are:
requireUser
function in every authenticated layout? For example, I have the nested route structure,/dashboard/events
and/dashboard/events/create
. Do I need to call therequireUser
function in the parent layouts and all child routes or do I only need to add it in the parent layout? Are there any gotchas for when I only add it in the layout? I know react router will load the data in parallel and revalidate so I should be covered if I only load it in thedashboard.tsx
layout file right?requireAuthentication
which only checks the authentication and redirects if user is not logged in just like therequireUser
function but does not fetch the user details from the database? Is this a good practice especially if I need to add authentication calls to all my loaders in nested routes and layouts at least to ensure that on pages where I want to require authentication but I don't want to get the user details, I am not making that extra database call?In general, what is the best practice around authentication checks? Do I do it in my layouts only, will that suffice for all authenticated nested routes or do I need to do it in all layouts and nested authenticated routes?
Of course, for my actions, I am also making the check once more to make sure it's an authenticated request.
Beta Was this translation helpful? Give feedback.
All reactions