javascript / expert
Snippet
Global CSRF Protection via Functional Interceptors
Security at scale requires automated token management. This functional interceptor extracts the CSRF token from cookies and attaches it to every outgoing HTTP request, ensuring the backend can verify the authenticity of the client request.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { HttpInterceptorFn, HttpRequest, HttpHandlerFn } from '@angular/common/http';import { inject } from '@angular/core';import { DOCUMENT } from '@angular/common';export const csrfInterceptor: HttpInterceptorFn = (req, next) => {const doc = inject(DOCUMENT);const token = doc.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('=')[1];if (token) {req = req.clone({ setHeaders: { 'X-XSRF-TOKEN': token } });}return next(req);};
angular
Breakdown
1
HttpInterceptorFn
The modern functional type definition for intercepting and modifying HTTP requests and responses.
2
inject(DOCUMENT)
Safely injects the global document object, adhering to Angular's platform abstraction layer.
3
req.clone({ setHeaders: ... })
HttpRequest objects are immutable; clone() is used to create a modified copy with new headers.