Blog>
Snippets

Handling CORS in Angular for security

Demonstrate the best practices to handle Cross-Origin Resource Sharing (CORS) in Angular to prevent unauthorized API access.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CORSInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header.
    const corsReq = req.clone({
      headers: req.headers.set('Access-Control-Allow-Origin', '*')
    });

    // Send the newly created request
    return next.handle(corsReq);
  }
}
This is a basic example of an Angular HTTP Interceptor that modifies outgoing HTTP requests to include the 'Access-Control-Allow-Origin' header. However, setting the header on the client-side does not address security or proper CORS handling. CORS policies should be managed server-side.
// In your module (e.g., app.module.ts)
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CORSInterceptor } from './cors.interceptor'; // adjust the path to where your interceptor is

@NgModule({
  declarations: [
    // your components here
  ],
  imports: [
    HttpClientModule,
    // other imports here
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: CORSInterceptor, multi: true },
    // other providers here
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
This code is meant to be placed in an Angular module to provide the CORSInterceptor service globally by adding it to the HTTP_INTERCEPTORS array. This sets up the interceptor to process all outgoing HTTP requests.