Blog>
Snippets

Configuring CSRF Protection in Angular with HttpClientXsrfModule

Demonstrate how to configure CSRF protection in Angular by importing HttpClientXsrfModule with custom header and cookie names.
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'MY_CSRF_COOKIE', // Replace with your CSRF cookie name
      headerName: 'MY_CSRF_HEADER'  // Replace with your CSRF header name
    })
  ]
  /* ... other module properties ... */
})
export class AppModule { }
This code imports the HttpClientXsrfModule and configures it in an Angular module by specifying custom cookie and header names for CSRF protection. The 'cookieName' option sets the name of the CSRF token cookie Angular looks for, and the 'headerName' option sets the name of the HTTP header that Angular will add the CSRF token to when sending HTTP requests. These should match the names expected by the server.