Tips to Secure Your Angular Application
Estimated study time: 8 minutes. Practical steps to keep your Angular app and its users safe.
Angular includes solid security defaults, but it's still on you to use them correctly and avoid common mistakes.
1. Trust Angular's Built-in XSS Protection
Angular automatically sanitizes values bound in templates. Avoid bypassing this with bypassSecurityTrustHtml unless you fully control and trust the source of that content.
2. Never Store Sensitive Tokens in localStorage
Access tokens stored in localStorage are readable by any script running on the page, including injected malicious scripts. Prefer secure, httpOnly cookies managed by your backend where possible.
3. Use HttpInterceptors for Auth Headers
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${this.authService.getToken()}` }
});
return next.handle(authReq);
}
}
4. Guard Your Routes
Use route guards (CanActivate) to prevent unauthorized users from reaching protected pages, and always validate permissions on the backend too — client-side guards are a UX layer, not a security boundary.
5. Keep Dependencies Updated
Run ng update and audit dependencies regularly (npm audit) to catch known vulnerabilities in third-party packages before they become a problem.
6. Enforce HTTPS and Strict CSP
Serve your app only over HTTPS and configure a strict Content Security Policy on the server to limit what scripts and resources are allowed to load.