Protecting routes in Angular ๐ฎโโ๏ธ

I'm a full-stack developer from South Africa ๐ฟ๐ฆ. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa ๐ฟ๐ฆ. I love writing about JavaScript, HTML and CSS.
Great stuff! Would also love to see articles on how to write unit tests for each of these articles! :)
Hey Braydon, thank you so much! I really need to step up my unit testing game (to write actually useful tests) so let's work on that soon! โจ
Braydon Coyer That would be amazing Braydon! Let me know how we can progress that!
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

Protecting specific routes in Angular is a common use-case. Most applications will have some logged in section.
Yesterday we created a login service, so that someone can log in to our application.
But having this, we are also able to go to the home route not being logged in.
That's weird because we don't have a user and see nothing.

Let's fix that and make home a protected route.
Firs let's open the terminal and generate a new service.
ng generate service guards/AuthGuard
This will generate the auth.guard service inside the guards folder.
import { Injectable } from "@angular/core";
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
} from "@angular/router";
import { AuthService } from "../services/auth.service";
@Injectable({providedIn: 'root'});
export class AuthGuardService implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authService.userValue;
if (currentUser) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
We make use of the CanActivate method to intercept if this route can become active. We will place this in the routing in a second.
Then we overwrite this actual function and check if we have a current user value in our authService.
If we do, it's fine, and the route can return true (valid route). Else we redirect the user to the login page.
To implement the auth guard we just created, we need to modify our app-routing.module.ts.
import { AuthGuardService } from './guards/auth-guard.service';
const routes: Routes = [
// Other routes
{ path: 'home', component: HomeComponent, canActivate: [AuthGuardService] },
];
You see it's as simple as passing the canActive option with out custom AuthGuardService.
Now, if we visit the home page without being logged in, we will be redirected to login.
Once we log in, we will be able to see the page.

You can also find this code on GitHub.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter