From c5cb336049628aa60e411441114fbd9264682645 Mon Sep 17 00:00:00 2001 From: Marcin-Ramotowski Date: Sun, 13 Apr 2025 13:38:43 +0200 Subject: [PATCH] Added interceptor to dynamically set CSRF token header --- frontend/src/api/api.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/frontend/src/api/api.ts b/frontend/src/api/api.ts index 18cc4a4..c15efef 100644 --- a/frontend/src/api/api.ts +++ b/frontend/src/api/api.ts @@ -7,10 +7,28 @@ const api = axios.create({ baseURL: API_URL, headers: { "Content-Type": "application/json", - Accept: "application/json", - "X-CSRF-TOKEN": Cookies.get("csrf_access_token") + Accept: "application/json" }, withCredentials: true, }); +// Interceptor – before sending the request +api.interceptors.request.use( + (config) => { + // For data update methods, add CSRF token + const method = config.method?.toUpperCase(); + const modifyingMethods = ["POST", "PUT", "PATCH", "DELETE"]; + + if (method && modifyingMethods.includes(method)) { + const csrfToken = Cookies.get("csrf_access_token"); + if (csrfToken) { + config.headers["X-CSRF-TOKEN"] = csrfToken; + } + } + + return config; + }, + (error) => Promise.reject(error) +); + export default api;