Search code examples
angularauth0ngoninit

Checking for authentication status and redirecting user


In my app component, I want to check if the user is authenticated as soon as it loads and if not redirect the user to a public page immediately instead of loading the home (profile) page. I'm using the Auth0 service that can be found here: link to GitHub file

The question is, should I run this in the constructor or in ngOnInit and why?

if (auth.isAuthenticated()) {
  router.navigateByUrl(...))
}

Solution

  • In general, you should avoid putting any business logic in the constructor of components or directives.

    Why?

    Because, at the time when the constructor for a component is run, Angular has not yet initialized any inputs that component (or directive) may have. So, if the initialization logic depends on the value of its inputs, those inputs will not have their correct values, resulting in incorrect business logic.

    But my component/directive initialization doesn't depend on its inputs!!

    That may be true now, but if/when that changes, you now have to remember to move all your logic from the constructor to ngOnInit, which is just asking for trouble. And then, you'd have this inconsistency where some components use the constructor for initialization logic and others use ngOnInit, and that unnecessary inconsistency is also just asking for trouble as your application develops. It's the same reason why the strong recommendation is to always add the @Injectable decorator on all services even if you technically only need it if your service uses dependency injection - add it always so you don't forget to do it later when you actually do need it.

    TLDR;

    For consistency and to save yourself debugging problems later, only use your constructor in your components to capture injectables as properties - put all your other logic in ngOnInit.

    NOTE

    As @DeborahK pointed out, however, in this specific situation where you want to essentially prevent a component from being routed to if a certain condition is not met, a better solution may be a router guard. This feature of the router prevents the component from being initialized at all if some condition is not met.