![]()
AngularJS is a powerful frontend framework but is no longer actively maintained, making security and best practices crucial to maintaining a secure, high-performance application. This guide provides best practices and security tips for optimizing and securing your AngularJS application.
2. Best Practices for AngularJS Applications
2.1 Use Component-Based Architecture
Instead of using controllers, prefer components for better maintainability and modularity.
Use AngularJS 1.5+ Components
app.component('myComponent', {
template: `<h1>Hello, {{ $ctrl.name }}</h1>`,
controller: function() {
this.name = "AngularJS";
}
});
Avoid Using Controllers and $scope (Legacy Approach)
app.controller('MyController', function($scope) {
$scope.name = "AngularJS";
});
2.2 Follow Modular Development
Divide your application into small, reusable modules to improve code maintainability.
Use AngularJS Modules Properly
var userModule = angular.module('userModule', []);
var productModule = angular.module('productModule', []);
var app = angular.module('myApp', ['userModule', 'productModule']);
2.3 Use $http Service Instead of jQuery AJAX
Always prefer $http service for API calls, as it integrates well with AngularJS’s digest cycle.
Correct Way
app.service('UserService', function($http) {
this.getUsers = function() {
return $http.get('/api/users');
};
});
Avoid Using jQuery AJAX in AngularJS
$.ajax({
url: "/api/users",
success: function(response) {
console.log(response);
}
});
2.4 Optimize Performance with $watch and $digest
Excessive use of $watch can slow down your app. Use one-time binding (::) where possible.
Use One-Time Binding for Static Data
<h1>{{ ::user.name }}</h1>
Avoid Using Too Many $watch Statements
$scope.$watch('user.name', function(newVal, oldVal) {
console.log('User name changed!');
});
2.5 Use Lazy Loading for Modules
Lazy load modules using AngularJS Route Providers to improve initial load time.
Example: Lazy Loading Modules
app.config(function($routeProvider) {
$routeProvider.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardController',
resolve: {
loadController: function($q, $ocLazyLoad) {
return $ocLazyLoad.load('dashboardController.js');
}
}
});
});
2.6 Enable Debugging Only in Development
Disable debugging tools in production to improve security and performance.
Disable Debug Info in Production
app.config(function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});
Avoid Using Debugging Tools in Production
angular.reloadWithDebugInfo();
3. Security Tips for AngularJS Applications
3.1 Prevent Cross-Site Scripting (XSS) Attacks
XSS attacks occur when malicious scripts are injected into the application.
Use $sce (Strict Contextual Escaping) for Binding HTML
app.controller('SafeController', function($scope, $sce) {
$scope.safeHtml = $sce.trustAsHtml('<p>This is safe HTML</p>');
});
Avoid Using ng-bind-html with Untrusted Data
<div ng-bind-html="userInput"></div> <!-- XSS Vulnerability -->
3.2 Prevent Cross-Site Request Forgery (CSRF)
Use CSRF tokens to protect against unauthorized API requests.
Enable CSRF Protection in $http
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
});
3.3 Avoid Using eval() and $eval
The eval() function can execute arbitrary JavaScript code, making it a major security risk.
Do Not Use eval() in AngularJS
$scope.result = eval($scope.userInput); // Security Vulnerability
Use AngularJS Expressions Instead
<p>{{ userInput | uppercase }}</p>
3.4 Prevent Injection Attacks (SQLi, NoSQLi, etc.)
- Always sanitize user input before sending data to the backend.
- Use parameterized queries on the server side.
Example: Sanitizing User Input
app.controller('InputController', function($scope) {
$scope.sanitize = function(input) {
return input.replace(/[<>]/g, ""); // Removes dangerous characters
};
});
3.5 Implement Content Security Policy (CSP)
CSP helps prevent XSS and other script-based attacks.
Set HTTP Headers for CSP
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
3.6 Restrict Third-Party Library Usage
- Avoid outdated third-party libraries with known vulnerabilities.
- Regularly check dependencies using npm audit.
Use npm Security Audit
npm audit
3.7 Disable Automatic URL Parsing
AngularJS automatically parses URLs in certain directives (ng-href, ng-src), which can be exploited.
Use $sce for URL Sanitization
$scope.safeUrl = $sce.trustAsResourceUrl('https://trustedsource.com');
3.8 Use JWT for Authentication Instead of Cookies
JWT (JSON Web Token) provides a more secure authentication method than cookies.
Example: Sending JWT in Headers
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
3.9 Prevent Clickjacking Attacks
Use X-Frame-Options header to prevent your app from being embedded in an iframe.
Set X-Frame-Options in HTTP Response
X-Frame-Options: DENY
