![](https://dontpaniclabs.com/wp-content/uploads/2021/03/angular-guards.jpg)
Angular Guards: Getting Started
The Angular Router is a powerful tool in our Angular toolbox. Part of the Angular Router is guards. When guards are configured, they can be used to block access to individual routes within our Angular SPA. Think of it as a way to prevent users from viewing specific screens within the client-side application. This guard is entirely client side, so it isn’t real security.
To create a guard, you can use the Angular CLI.
ng generate guard guards/authenticated
That will generate a guard that we can change. We can use this guard to block access to some routes. While it can also stop a user from leaving a route, we will just focus on blocking access to a route in this post.
We can now add our guard to one of our routes. If our guard returns false, we will not be able to access the route. If the guard returns “true”, we will have access.
If we change our to return “false”, we will not be able to return navigate.
Guards are not the most amazing piece of software. However, layering in appropriate guards should be part of any SPA you build.
I do have a few recommendations on using guards:
- They are not real security; you must still validate the user on the backend.
- Don’t add a lot of logic to API calls in your guard; this can cause slow and unpredictable behavior.
- Don’t have too many guards; keep it straightforward if you can.