Secure navigation in Angular with functional route guards
Using Angular guards to protect routes gives an Angular single-page application a deliberate way to respond to who is signed in and what they may reach. A guard can stop navigation, send the browser to another route, or wait while an application restores its session. That makes it more than a convenience for hiding menu links: it becomes part of the application’s navigation contract.
Modern Angular favours functional guards built with CanActivateFn and related types. They run inside Angular’s injection context, so a guard can obtain services with inject() without needing a class hierarchy or constructor boilerplate. A guard may return a boolean, a UrlTree, or a promise or observable that resolves to either, which covers simple allow-or-block policies and redirects with the router’s own navigation model.
For Australian teams, this is more than sample-project plumbing. Banking, health, government and e-commerce products commonly carry identity or sensitive data, and where the Privacy Act 1988 applies, the Australian Privacy Principles influence what may be collected and logged. A product might be developed in Brisbane for customers in Sydney and Melbourne, with a Perth colleague joining after hours. Guard design should cope with distant users, intermittent mobile connections and strict expectations around personal information.
Why route guards belong in your navigation design
A route guard is a client-side navigation policy, not an API security boundary. It can stop a user from opening an account page or display a more suitable screen, but anyone can alter a request outside the browser. The server must still verify the session and authorise every protected operation. Treat the guard as a fast, user-friendly layer over the real security controls rather than as the only control.
That distinction is particularly important for Australian regulated sectors. A role displayed in a navigation menu does not prove that the person can approve a payment, view a clinical record or alter a government workflow. The API must apply least privilege, check current permissions and record an appropriate audit event. The guard should mirror that policy in the interface while keeping sensitive identifiers out of URLs, logs and analytics wherever possible.
Matching guards to navigation decisions
Angular provides different guards for different questions. canActivate decides whether a route can be entered, canActivateChild protects child routes, canDeactivate runs before leaving a route, and canMatch determines whether a route configuration matches at all. Returning false cancels or skips navigation; returning a UrlTree redirects to a deliberate destination. These behaviours are more predictable than scattering window.location calls through components.
A typical route table can combine them without making the application brittle:
export const routes: Routes = [
{ path: 'sign-in', component: SignInPageComponent },
{
path: 'account',
component: AccountShellComponent,
canActivate: [signedInGuard],
children: [
{ path: 'details', component: AccountDetailsComponent },
{
path: 'orders',
component: OrdersComponent,
canActivateChild: [signedInGuard]
}
]
},
{
path: 'admin',
canMatch: [signedInGuard, adminGuard],
loadComponent: () =>
import('./admin/admin-page.component')
.then(m => m.AdminPageComponent)
},
{ path: '**', component: NotFoundPageComponent }
];
canMatch is useful with lazy loading because a denied user does not need to download the protected feature bundle. A false result lets the router try another matching route, while a UrlTree can send the user to sign-in or a forbidden page. Leaving a route with unsaved work is a separate concern and is better handled by canDeactivate.
Restoring sessions without redirect races
The first problem to solve is often authentication state. If the application starts with a null user, checks that value and immediately redirects, it may reject a valid user whose cookie-backed session is still being restored. Give the guard an explicit session-restoration step and cache the shared result:
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly api = inject(SessionApi);
private readonly currentUser = signal<User | null>(null);
private session$?: Observable<User | null>;
readonly user = this.currentUser.asReadonly();
ensureSession(): Observable<User | null> {
this.session$ ??= this.api.restoreSession().pipe(
tap(user => this.currentUser.set(user)),
shareReplay({ bufferSize: 1, refCount: false })
);
return this.session$;
}
}
The guard then waits for that observable before choosing a result:
export const signedInGuard: CanActivateFn = (_route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.ensureSession().pipe(
map(user =>
user
? true
: router.createUrlTree(['/sign-in'], {
queryParams: { returnUrl: state.url }
})
)
);
};
This matters during ordinary Australian mobile use: someone in Sydney may open an emailed order link while on a train between stations. Waiting briefly for session restoration avoids bouncing that person to sign-in and back again. Keep the session in a secure, HttpOnly, SameSite cookie where possible, and use an OAuth flow with PKCE for third-party sign-in rather than placing long-lived access tokens in local storage. Validate any returnUrl before navigating so it points only to an internal route, and avoid placing customer identifiers or other sensitive values in query strings.
Combining authorisation and exit protection
Authentication establishes identity; authorisation decides what that identity may do. A separate functional guard can check a role after the session has been restored:
export const adminGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.user()?.roles.includes('operations-admin')
? true
: router.createUrlTree(['/not-authorised']);
};
Role claims can be stale, so the API must repeat the permission check for each protected action. The browser guard improves the interface and may avoid loading an unauthorised feature, but it cannot prevent a crafted request. Hide unauthorised navigation links as a convenience, while keeping the destination and the server response safe for direct access.
Unsaved work needs a guard for the opposite transition. This example asks before leaving an editor and supports a promise-based confirmation service:
export const unsavedChangesGuard:
CanDeactivateFn<OrderEditorComponent> = component => {
const dialog = inject(ConfirmDialogService);
return component.hasUnsavedChanges
? dialog.confirm('Discard unsaved changes?')
: true;
};
Good exit protection explains what will be lost and keeps the current page when the user cancels. It also works for browser navigation, not just an in-app back button. Apply the same privacy care to route telemetry: a full URL may contain an account number, invoice reference or reset token, so record a route template or identifier where the Privacy Act and applicable state or territory records laws allow.
Practical safeguards for Australian delivery teams
Before shipping route protection, document which routes are public, session-only, role-restricted or available while offline. Then review the implementation against the Australian Privacy Act 1988, the Australian Privacy Principles and the security baseline used by the organisation, such as the ACSC Essential Eight. Those frameworks do not replace application-specific access rules, but they provide useful prompts for data minimisation, logging and incident response.
- Keep server-side authorisation absolute and re-check permissions for every protected operation; use the client guard only to shape navigation.
- Resolve or refresh the session before making an allow-or-deny decision, and show a loading state instead of redirecting while identity is unknown.
- Prefer a
UrlTreefor redirects so Angular retains consistent navigation behaviour, and make sure public routes cannot form a redirect loop. - Preserve intended destinations with a validated internal
returnUrl, and keep tokens, reset links and personal identifiers out of it. - Choose
canActivate,canActivateChild,canDeactivateandcanMatchaccording to the transition being protected rather than applying one broad guard everywhere. - Test anonymous, expired, permitted and forbidden sessions, including refresh, deep links, browser back navigation and a role change during an open session.
A small decision table can make reviews faster: record the route, required state, redirect destination, server check and expected telemetry for each one. It also gives teams in different Australian time zones a shared definition of “authorised”. Confirm that unauthorised screens do not reveal record details, that error logs do not capture full URLs unnecessarily, and that any email or SMS triggered after access follows the Australian Spam Act 2003 when commercial consent is required.
Start with one customer-facing area rather than attempting to guard every route in a single release. Add the session-aware sign-in guard to the account route, write tests for a valid session, an expired session and a denied role, then exercise a deep link in a browser test. That gives the team a concrete navigation flow to review.
When the flow behaves correctly, add the role and unsaved-change guards only where the application needs them, repeat the checks in continuous integration, and ship the protected area. Small, observable releases make regressions easier to trace and keep the guard policy aligned with the API’s authorisation rules.