Single route with Guest and Auth middleware

Is this possible in Adonis Js to make a single route sometimes Guest and sometimes Auth on condition.

like when register has value role_id = 1 in request this does not require Auth middleware, however when role_id =2 it check Authentication'register', 'AuthController.register')'register', 'AuthController.register')..middleware(['auth'])
1 Like

I advise you to create a custom middleware with auth object. Like:

async handle({ response, auth, request }, next) {
  // call next to advance the request
  const role = request.input('role_id')
  if(role == 2){
    try {
	await auth.check();
    } catch (error) { ... }
  await next();

Do we always call .middleware[‘auth’] on routes even when we have a customAuth?

Basically, if we make a custom auth as below, do we still use middleware[‘auth’,‘customAuth’] or is middleware[‘customAuth’] on that route fine.

Custom Auth

try {
	await auth.check();
	return view.render('/home')
    } catch (error) { 
return view.render('auth/login') 

If you create your own authentication middleware you don’t need to use the default one. But of course, we mustn’t forget: await auth.check(); :wink:

For your example, you don’t need to use middleware auth

You might be interested in this: auth middleware source code


Thanks for the help, my issue is solved now!

1 Like

Got another strange problem, allowed to post here?

Regards, vlc

@annejones101 if it’s a specific question you can create a new topic

And welcome to our community :smiley: