How to prevent CSRF attacks when you’re an Angular developer

Cross-Site Request Forgery (CSRF) attacks are a type of security vulnerability that can affect web applications. Angular developers need to be aware of the risks of CSRF attacks and take measures to prevent them. In this tutorial, we will discuss how to prevent CSRF attacks in Angular applications.

Use Angular’s built-in CSRF protection:

Angular provides built-in CSRF protection that automatically generates anti-CSRF tokens and includes them in all HTTP requests. The HttpClientXsrfModule module is responsible for this feature. You can enable this module by adding it to your application’s root module as shown below:

import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';

  imports: [
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-XSRF-TOKEN'
  // other module configuration
export class AppModule { }

This code enables the HttpClientXsrfModule and sets the cookie and header names for the anti-CSRF token.

Include the anti-CSRF token in forms and AJAX requests:

To ensure that the anti-CSRF token is included in all HTTP requests, you need to add it to forms and AJAX requests manually. Angular provides a built-in HttpClient service that you can use to send HTTP requests with the anti-CSRF token.

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

submitForm() {
  const token = this.tokenService.getToken();
  const headers = { 'X-XSRF-TOKEN': token };
  const body = { data: 'example data' };'/api/submit', body, { headers }).subscribe(response => {
    // handle response

This code sends an HTTP POST request to /api/submit with the anti-CSRF token included in the request headers.

Use SameSite cookies:

SameSite cookies restrict the cookie’s availability to a particular website. By setting the SameSite attribute to “Strict” or “Lax”, you can prevent CSRF attacks by ensuring that the browser only sends the cookie to the website it originated from.

To set SameSite cookies in Angular, you can use the ngx-cookie-service package.

import { CookieService } from 'ngx-cookie-service';

constructor(private cookieService: CookieService) {}

setCookie() {
  this.cookieService.set('session_id', '123', null, '/', null, true, 'Strict');

This code sets a SameSite cookie with the name session_id, value 123, and SameSite attribute set to “Strict”.


CSRF attacks can be prevented by using Angular’s built-in CSRF protection, including the anti-CSRF token in forms and AJAX requests, and using SameSite cookies. By following these best practices, you can ensure that your Angular application is safe and secure from CSRF attacks.

You may also like...