Route for guest *and* authenticated users

Hi there!

I’m trying to have a route that is valid both for guest users and users that are logged in. The hitch is that, if the user is logged in, I still want to know which user she is - so my controller can respond slightly differently.

It appears if I use the “guest” middleware, then logged in users can’t use that route, and if I use the “auth” middleware, obviously, guests can’t access the route.

If I use no middleware at all, then both types of users have access to the route, but auth.user is undefined since the auth middleware wasn’t involved…

Am I forced to use different routes for guests and logged in users?


1 Like

Skip the middleware, and within your controller do like so:

try {
  auth.user = await auth.getUser()
} catch(e) {}

// ... blah blah blah...

if (auth.user) {
  // authenticated differences
} else {
  // unauth stuff

You need the try/catch because getUser will throw an exception if it doesn’t succeed… but in your case you can simply ignore and continue on, auth.user will be null if the user isn’t authenticated.

Alternately, you could create your own middleware that do that try/catch logic if this is going to apply to several routes, then it’s reusable as necessary…


Brilliant! I somehow missed the “getUser” function - that is exactly what I needed, thank you!

This post was flagged by the community and is temporarily hidden.