Home > database >  Remix authentication and nested route loaders
Remix authentication and nested route loaders

Time:01-17

I have a Remix app with routes like defined below, where I want a, b and c to be authenticated routes:

root/
└── a/
    ├── b
    └── c

In route a loader I check for an authenticated user:

// in a.tsx, inside `loader` function
authenticator.isAuthenticated(
  {...},
  failureRedirect: '...'
)

This works fine since loading /a/b triggers a loader, which redirects upon auth failure.

But do I also need to do the check authentication in loaders for routes b and c?

Since a loader is not triggered when navigating from /a/b to /a/c, is it safe to assume in c loader that user is authenticated? And if not, what's the Remix way? Calling isAuthenticated in every segment would be very cumbersome.

Thanks

CodePudding user response:

Yes. With Remix, each route loader is independent. They will be called in parallel, and sometimes your ancestor loaders won't even be called.

So generally, you should protect each loader. Typically this is done via a function like const user = await requireUser(request)

The function would validate that you have a logged-in user and throw a redirect to the login page if not.

I also add a check in my express entry to see if I have the auth token before handing the request to Remix. I have a whitelist of public routes. This way ALL routes are protected by default, and I have to specifically opt out.

Anyway, Remix is working on adding a beforeLoader export for this type of scenario. https://github.com/remix-run/react-router/discussions/9564

  • Related