Router Guards

In this lesson, we'll learn how router guards can prevent users from visiting routes they're not supposed to.

We'll cover the following

We’re almost finished with authentication. One last thing we’ll implement is restricting access to specific routes in our application. Even though we’re not displaying the link to the secret page, users are technically still able to view the page if they input the URL in their address bar. The same applies vice versa. We don’t want to show the user the login or registration pages if they are logged in.

We can resolve these issues with router guards. A router guard is a class that runs before the component for the route loads. Angular will wait for a return value from the guard. The guard must return a boolean value. If the value is true, the component for the route will load. If the value is false, then the request is rejected. Router guards are the recommended way to restrict access to routes.

Auth guards

Creating a guard can be tricky. Luckily, we don’t have to create one. The Angular Firebase package that we installed comes with a guard that can be customized for restricting access based on the authentication status. Guards can be applied to individual routes by adding a property called canActivate.

In the app-routing.module.ts file, we’ll update the routes array to the following:

Get hands-on with 1200+ tech skills courses.