How to create auth guard in Angular Fire v7 with new API (not compat)

Viewed 27

I faced error

TypeError: Unable to lift unknown Observable type

when trying to use v7 Angular Fire with the new API.
Specifically "@angular/fire": "^7.4.1" which is angular 14, firebase 9.
Note, as a deliberate choice not recommended by developers, I'm not using compat imports anywhere in my app.

import { User } from '@angular/fire/auth';
import { AuthGuard, AuthPipe, AuthPipeGenerator } from '@angular/fire/auth-guard';

const redirectUnauthorizedAndUnverifiedToAuth: AuthPipe = map((user: User | null) => {
  // if not logged in, redirect to `auth`
  // if logged in and email verified, allow redirect
  // if logged in and email not verified, redirect to `auth/verify`
  return !!user ? (user.emailVerified ? true : ['auth', 'verify']) : ['auth']
})

const routes: Routes = [
  {
    path: "auth",
    loadChildren: () => import("./auth/auth.module").then(m => m.AuthModule)
  },
  {
    path: "my-feature",
    loadChildren: () => import("./my-feature/my-feature.module").then(m => m.MyFeatureModule),
    canActivate: [AuthGuard],
    data: { authGuardPipe: redirectUnauthorizedAndUnverifiedToAuth }
  },
  { path: "", redirectTo: "auth", pathMatch: "full" },
  { path: "**", redirectTo: "auth" }
];
1 Answers

Caveat at time of writing https://github.com/angular/angularfire#developer-guide

AngularFire has a new tree-shakable API, however this is still under active development and documentation is in the works, so we suggest most developers stick with the Compatiability API for the time being.

The new API expects an AuthPipeGenerator rather than AuthPipe despite the name authGuardPipe.

https://github.com/angular/angularfire/blame/master/src/auth-guard/auth-guard.ts#L21

const authPipeFactory = next.data.authGuardPipe as AuthPipeGenerator || (() => loggedIn);

Type definitions found at import { AuthPipe, AuthPipeGenerator } from '@angular/fire/auth-guard';

Solved by

const authPipeGenerator: AuthPipeGenerator = () => redirectUnauthorizedAndUnverifiedToAuth

const routes: Routes = [
  ...
  {
    path: "my-feature",
    ...
    data: { authGuardPipe: authPipeGenerator }
  },
Related