skip to content
Alvin Lucillo

Auth0 guard

/ 1 min read

Auth0 guard from Angular SDK helps ensure your route access is for only those authenticated successfully in auth0 instead of checking it manually. If the user is not logged in, the guard redirects them to the login page.

To set that up, add the guard in app.routes.ts. In this case, the profile page requires authenticated access.

export const routes: Routes = [
	{
		path: "",
		component: Home,
	},
	{
		path: "profile",
		component: Profile,
		canActivate: [AuthGuard],
	},
];

profile.ts

@Component({
	selector: "app-profile",
	imports: [AsyncPipe],
	template: `
		<h1>Profile</h1>

		@if (auth.user$ | async; as user) {
			<p>Name: {{ user.name || "Unknown" }}</p>
			<p>Email: {{ user.email || "Unknown" }}</p>
		}
	`,
})
export class Profile {
	protected readonly auth = inject(AuthService);
}