Guarding Guest Routes

In this lesson, we'll redirect the user away from the login and registration forms if they are logged in.

We'll cover the following

We’re going to add another router guard for routes that are for guests only. We want to redirect the user to the secret page if they are already logged in. The process will be similar to before. We’ll apply a guard to the route with a pipe to change its behavior. Let’s get started.

Creating a pipe

We’ll be using the AngularFireAuthGuard again. Before we do, let’s create the pipe to modify its behavior. The AngularFire package comes with a pipe, called redirectLoggedInTo, to redirect the user if they are logged in.

In the app-routing.module.ts file, we’ll update the import statement to include this pipe and create a function for generating the pipe.

import { AngularFireAuthGuard, redirectUnauthorizedTo, redirectLoggedInTo } from '@angular/fire/auth-guard';

const authOnly = () => redirectUnauthorizedTo(['']);
const guestOnly = () => redirectLoggedInTo(['secret']);

In the snippet above, we’re defining a function called guestOnly. Its value will be the pipe generated by the redirectLoggedInTo. We can customize the pipe by passing an array of paths to which we’d like the user redirected. In this instance, we’ll redirect them to the secret page.

Updating the routes

Let’s update the routes array to use the guard.

const routes: Routes = [
  {
    path: '',
    component: LoginComponent,
    canActivate: [AngularFireAuthGuard],
    data: { authGuardPipe: guestOnly }
  },
  {
    path: 'register',
    component: RegisterComponent,
    canActivate: [AngularFireAuthGuard],
    data: { authGuardPipe: guestOnly }
  },
  {
    path: 'secret',
    component: SecretComponent,
    canActivate: [AngularFireAuthGuard],
    data: { authGuardPipe: authOnly }
  },
  { path: 'logout', component: LogoutComponent }
];

The routes we’re making changes to are for the homepage and register page. On both routes, we’re setting the canActivate property to AngularFireAuthGuard and authGuardPipe to guestOnly. This should result in the user being redirected to the secret page if they are logged in.

Here’s the updated code:

Get hands-on with 1400+ tech skills courses.