This content originally appeared on DEV Community and was authored by Rohit Singh
When building modern web applications, security is non-negotiable. Angular provides a strong foundation with built-in security features, but careless code or overlooked configurations can still leave your app vulnerable.
In this article, weβll walk through the most important Angular security best practices, complete with real-world examples to help you write safer applications.
- Prevent Cross-Site Scripting (XSS) The Threat
XSS attacks happen when malicious scripts are injected into your application, often via user input fields.
Angularβs Protection
Angular automatically sanitizes HTML to prevent XSS. However, problems arise when using [innerHTML] or bypassing sanitization.
Bad Example
<div [innerHTML]="userComment"></div>
If userComment = “alert('Hacked!')”, it could execute malicious code.
Safe Example
<div [innerHTML]="sanitizedComment"></div>
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer) {}
this.sanitizedComment = this.sanitizer.bypassSecurityTrustHtml(userComment);
Use DomSanitizer carefully, only when you trust the content.
- Avoid eval() and Dynamic Code Execution
Never use eval(), Function(), or setTimeout with dynamic strings. They can execute malicious scripts injected by attackers.
Bad Example
eval(userInput); // Executes attackerβs code!
Safe Example
Stick with Angular bindings and avoid dynamic execution entirely.
- Use Angularβs HttpClient (with Interceptors)
When making HTTP requests, avoid direct string concatenation in URLs or headers.
Example
this.http.get(`/api/users/${encodeURIComponent(userId)}`);
Also, use HTTP Interceptors to:
Attach authentication tokens securely
Handle errors globally
Add CSRF headers
- Implement Content Security Policy (CSP)
CSP adds an extra layer of protection against XSS by restricting what content can load.
Example index.html
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
This prevents scripts from running if theyβre not from your own domain.
- Secure Authentication & JWT Handling
Store JWT tokens in HttpOnly cookies instead of localStorage (to reduce XSS risks).
Always validate tokens on the server.
Use Angular Route Guards to protect routes.
Example Guard
canActivate(): boolean {
return !!this.authService.getToken();
}
- Use Angular Sanitization for URLs
Avoid directly binding untrusted URLs into links or iframes.
Bad Example
<a [href]="userUrl">Click</a>
Safe Example
safeUrl = this.sanitizer.bypassSecurityTrustUrl(userUrl);
<a [href]="safeUrl">Click</a>
- Keep Angular & Dependencies Updated
Many vulnerabilities are patched in new releases. Use:
ng update @angular/core @angular/cli
Also, run:
npm audit fix
to resolve dependency security issues.
- Use Strict Template Checking
Enable strict mode in tsconfig.json for stronger type safety:
{
"angularCompilerOptions": {
"strictTemplates": true
}
}
This prevents dangerous template expressions and reduces attack surfaces.
- Protect Against CSRF
If youβre using cookies for authentication:
Enable CSRF tokens on the backend.
Attach CSRF headers with Angular HttpInterceptor.
- Avoid Exposing Sensitive Data in Frontend
Never hardcode API keys, secrets, or database credentials in Angular codeβthey can be extracted easily.
Instead: store them on the server and use environment configs with Angular environments only for safe values.
Final Thoughts
Angular gives us powerful tools to build secure applicationsβbut security is a shared responsibility.
Always validate data both on the client and server, sanitize inputs, and stay up to date with Angular releases.
By following these best practices:
Youβll protect your app from XSS, CSRF, and data leaks.
Your usersβ data will stay safe.
Youβll build applications that inspire trust.
This content originally appeared on DEV Community and was authored by Rohit Singh