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.
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
If userComment = "alert('Hacked!')", it could execute malicious code.
โ Safe Example
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.
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.
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
CSP adds an extra layer of protection against XSS by restricting what content can load.
Example index.html
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.
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();
}
Avoid directly binding untrusted URLs into links or iframes.
โ Bad Example
Click
โ Safe Example
safeUrl = this.sanitizer.bypassSecurityTrustUrl(userUrl);
Click
Many vulnerabilities are patched in new releases. Use:
ng update @angular/core @angular/cli
Also, run:
npm audit fix
to resolve dependency security issues.
Enable strict mode in tsconfig.json for stronger type safety:
{
"angularCompilerOptions": {
"strictTemplates": true
}
}
This prevents dangerous template expressions and reduces attack surfaces.
If youโre using cookies for authentication:
Enable CSRF tokens on the backend.
Attach CSRF headers with Angular HttpInterceptor.
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.

๐ Rohit Singh ๐ โ Medium
Read writing from ๐ Rohit Singh ๐ on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.

medium.com
More...
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
If userComment = "alert('Hacked!')", it could execute malicious code.
โ Safe Example
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
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
Click
โ Safe Example
safeUrl = this.sanitizer.bypassSecurityTrustUrl(userUrl);
Click
- 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.

๐ Rohit Singh ๐ โ Medium
Read writing from ๐ Rohit Singh ๐ on Medium. Full-stack developer with 6+ years in Angular, Node.js & AWS. Sharing tips, best practices & real-world lessons from building scalable apps.
medium.com
More...