(2025-05-23T22:37:08.370Z) [All cookies via js-cookie:] 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:151:12
(2025-05-23T22:37:08.370Z) [useSignup.ts] csrf token from cookie: 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:235:12
(2025-05-23T22:37:08.372Z) [All cookies via js-cookie:] 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:151:12
(2025-05-23T22:37:08.372Z) [useSignup.ts] csrf token from cookie: 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:235:12
XHRGET
http://localhost:5000/api/api-security/csrf-token
[HTTP/1.1 200 OK 4ms]
(2025-05-23T22:37:08.449Z) [All cookies via js-cookie:] 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:151:12
(2025-05-23T22:37:08.449Z) [csrfServices.ts] Token from backend response: avMQZSykK-aT-VJSk0WhbZFVWvrZ3zLPEtAwInslFmYEt306bfBbjOKvZBPfIckD_iEXjr2ICoNBqVxMKWsuJA== loggerUtils.ts:151:12
(2025-05-23T22:37:08.450Z) [csrfServices.ts] Token from cookie: 0c9f439c83a3f38ceaa38988985ce2b9e873dee010ad5ed0d9d85522aa94ab97a:2:{i:0;s:5:"_csrf";i:1;s:32:"nDm_ATpjqV6ALdhnotMtdW8LSylnRN8B";} loggerUtils.ts:151:12
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
apiClient.interceptors.request.use(config =>
{
code
const token = csrfTokenManager.getToken();
code
if (token)
code
{
code
config.headers['X-CSRF-Token'] = token;
code
}
code
return config;
});
*/
export const CSRF_COOKIE_NAME = '_csrf';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};
/**
Fetch the CSRF token and param from the backend endpoint.
This triggers the backend to set the CSRF cookie.
Throws an error if token or param are missing.
*/
export async function fetchCsrfToken(): Promise
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
// wait 50-100ms to allow cookie to become available
await new Promise(resolve => setTimeout(resolve, 50));
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
/**
The backend sends the CSRF token in the JSON response as a plain string.
While the backend also sets a CSRF cookie (e.g., named 'csrfToken'), this cookie's value
is signed and serialized by the Yii framework to prevent tampering.
That means the cookie does NOT contain the raw token string but a protected value
including a signature and serialized data.
Because of that, attempting to read the CSRF token directly from the cookie on the frontend
and compare it with the token from backend JSON response will fail due to mismatched formats.
Therefore, it is best practice to trust the backend JSON token directly for sending in headers
and not attempt to read or validate the CSRF token from the cookie value.
This approach avoids dealing with Yii's cookie signing mechanics on the client side,
simplifies the CSRF token management,
and ensures synchronization without false mismatches.
*/
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
Returns undefined if cookie is missing.
*/
export function getCsrfTokenFromCookie(): string | undefined
{
logger.log('All cookies via js-cookie:', Cookies.get(CSRF_COOKIE_NAME));
return Cookies.get(CSRF_COOKIE_NAME);
}
/**
Clear old CSRF cookie
*/
export async function refreshCsrfToken(): Promise
{
// Optionally clear old cookie
Cookies.remove(CSRF_COOKIE_NAME);
// Now fetch new token; backend sets new signed cookie on response
return fetchCsrfToken();
}
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init(): Promise<void>
{
if (this.initPromise)
{
return this.initPromise;
}
this.initPromise = (async () =>
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;// Typically "_csrf"
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Overwrite with cookie token if present; note cookie value is signed string,
// but for consistency store it here.
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
})();
return this.initPromise;
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token (signed) if it exists because Yii validates against cookie
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
/* Optional setter if you want to manually update tokens
setToken(token: string, param?: string): void
{
this.csrfToken = token;
if (param)
{
this.csrfParam = param;
}
}//*/
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
Since I need both the backend return token for the csrf and the cookie at different times, then this code needs to be refactor to reflect this. The
backend code is:
code
Assistant
Thanks for sharing all the details and context. Your key challenge is that:
The backend returns a raw CSRF token string (csrfToken) in JSON via its actionCsrfToken() API.
The cookie (e.g., named _csrf or csrfToken) set by Yii is signed/serialized and not the raw token string.
Sometimes frontend code needs the raw token (for headers, forms, etc), sometimes needs the cookie (e.g., for sending as cookie or to let backend match).
Your current frontend code conflates these two tokens as if they're interchangeable, which they are not.
How to Refactor Your Frontend CSRF Service Properly
1. Separate cached values for:
The raw token from backend JSON response: the value you must send as header (X-CSRF-Token) for CSRF validation.
The signed cookie token read from the cookie: normally used indirectly by backend for validation, but you don't use or compare it directly.
Keep these two distinct.
2. Use the raw backend token as the source of truth for API requests.
Your frontend requests should add the X-CSRF-Token header with the raw token string from backend JSON.
Do not replace this token with the signed cookie value, because it will break the CSRF check.
3. Read the cookie token ONLY if you need to send the cookie to backend or inspect cookies.
Usually the browser does this automatically for cookie-based CSRF validation.
You typically do not need to set it manually.
4. Don't overwrite the raw token with cookie token in your cache, or your header sending will break.
Suggested Changes to Your CSRF Token Manager
Extracted ideas from your code + adaptation:
ts
User
"If you want, I can help you rewrite your entire csrfServices.ts file accordingly! Just let me know."
This is what I want, and also if it needs to be multi files, do so.
Assistant
Certainly! I will provide you with a clean, clear, and well-structured implementation of your CSRF token handling in the frontend. The key points we will implement:
Separate handling of raw CSRF token (from backend JSON) and signed Cookie token (from cookie).
Use raw token for all API request headers.
Read Cookie token only for info/logging or if needed for other edge cases.
Compatible with your backend Yii setup.
Proper async init on app start.
Clear type safety with TypeScript.
Rewritten CSRF Token Manager Service
Structure
We'll keep a single file csrfServices.ts since complexity is moderate, but it's modular and clear.
Neither — the important part is to consistently check for BOTH null and undefined in your code if you accept both:
ts
if (csrfToken != null) {
// This covers both null and undefined
// Safe to use csrfToken as string here
}
User
and to grab the cookie token that goes into the form i do what? useEffect? store it in use state
Assistant
Yes, exactly! To place the CSRF token (typically the raw token from backend JSON, not the signed cookie token) into a form (e.g., as a hidden input), the usual React pattern is:
On component mount, read the CSRF token from your CSRF token manager (that you initialized on app startup).
Store that token in component state (using useState).
Use useEffect to do this once when component mounts.
Then bind that state value as the value of your hidden input field.
Important
For forms you submit traditionally (not via Ajax), you must insert the raw CSRF token value (the one from backend JSON) into a hidden input named _csrf (or whatever your param name is).
The signed cookie token itself is generally not usable here.
Example usage in React component
tsx
import React, { useState, useEffect } from 'react';
import { csrfTokenManager } from '../services/csrfServices';
function MyForm() {
const [csrfToken, setCsrfToken] = useState<string | undefined>(undefined);
const [csrfParam, setCsrfParam] = useState<string | undefined>(undefined);
useEffect(() => {
// Fetch tokens from the csrfTokenManager singleton
setCsrfToken(csrfTokenManager.getRawToken());
setCsrfParam(csrfTokenManager.getParam());
}, []); // empty deps so runs once on mount
return (
<form method="post" action="/submit-endpoint">
{/* Hidden input with CSRF param name and raw token value */}
{csrfParam && csrfToken && (
<input type="hidden" name={csrfParam} value={csrfToken} />
)}
{/* your other form inputs here */}
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
Why use useEffect + useState?
Your CSRF tokens are fetched asynchronously on app init.
User
how do I clear setCsrfToken
Assistant
To clear the state value managed by setCsrfToken, simply set it to undefined (or null, depending on your typing), like this:
tsx
setCsrfToken(undefined);
or if your state accepts null:
tsx
setCsrfToken(null);
Example:
tsx
const [csrfToken, setCsrfToken] = useState<string | undefined>(undefined);
// To clear:
setCsrfToken(undefined);
// Now csrfToken will be undefined and your component will re-render accordingly.
When might you want to clear it?
On logout or user session end.
When refreshing tokens or removing form data.
When resetting the form or related state fully.
Tip: if your state is typed as string | undefined, prefer setting undefined to clear.
If typed as string | null, use null.
Let me know if you want help adding a reset or clear button example!
User
if I had setStep(0); which holds a number, how would I do a if statement if the the step set was 2?
Assistant
If you have a step state managed like this:
tsx
const [step, setStep] = useState<number>(0);
and you want to do an if statement to check if the current step is 2, you just do:
tsx
if (step === 2) {
// your logic here for step 2
}
Example usage inside a component:
tsx
function MyComponent() {
const [step, setStep] = useState<number>(0);
// somewhere in your code
if (step === 2) {
// do something when step is 2
}
// Or maybe inside JSX conditional rendering:
return (
<div>
{step === 2 && <p>You are on step 2!</p>}
<button onClick={() => setStep(2)}>Go to Step 2</button>
</div>
);
}
Summary
Use strict equality === to compare numeric state.
if (step === 2) { ... } works fine as expected.
Let me know if you want examples with switch statements or conditional rendering based on step!
User
import { csrfTokenManager } from './services/csrfServices';
async function bootstrapApp()
{
code
await csrfTokenManager.init();
code
// ... continue app startup
}
bootstrapApp();
I dont understand how to setup the csrfTokenManager
Assistant
No problem! Let me walk you through how to set up and use the csrfTokenManager in your app from scratch.
What is csrfTokenManager?
It’s a singleton service object that you import from csrfServices.ts which:
On init(), performs an async fetch to your backend /csrf-token API.
Fetches the raw CSRF token and param.
Caches the tokens internally.
Lets you get the current valid CSRF token for sending in headers or including in forms, via getter methods.
How to use csrfTokenManager
1. Import the manager where your app starts, for example your main entry file:
ts
import { csrfTokenManager } from './services/csrfServices';
2. Initialize it once at app startup:
You call init(), which returns a Promise you await before mounting or rendering your app, so tokens are ready.
Example:
ts
async function bootstrapApp() {
try {
await csrfTokenManager.init();
console.log('CSRF token manager initialized');
// Now continue loading your app, e.g. render React root or init routers
} catch (error) {
console.error('Failed to initialize CSRF token manager', error);
// handle error, maybe show UI or retry
}
}
bootstrapApp();
3. Use the token in API calls
Set up your Axios interceptor (or any fetch wrapper) to add the CSRF token header dynamically from the manager:
ts
import apiClient from './services/apiClientServices'; // your axios instance
import { csrfTokenManager } from './services/csrfServices';
apiClient.interceptors.request.use(config => {
const token = csrfTokenManager.getRawToken();
if (token) {
config.headers = config.headers || {};
config.headers['X-CSRF-Token'] = token;
}
return config;
});
User
// src/index.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import reportWebVitals from './reportWebVitals.ts';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/i18n';// i18n configuration
import App from './App';
// Root element must be set
const container = document.getElementById('root');
if (!container) {
code
throw new Error("Root element with id 'app' not found.");
}
const root = createRoot(container);
/**
React Strict Mode in Development
If your React app is wrapped in <React.StrictMode>, React intentionally mounts
components twice (only in development) to help detect side effects and bugs. This causes
effects like useEffect to run twice, which can lead to duplicate fetches.
Render App wrapped with I18nextProvider
*/
root.render(
<React.StrictMode>
</React.StrictMode>
);
// Optional: Report web vitals (for performance measuring)
reportWebVitals(console.log);
So in the index?
Assistant
Great! Your current src/index.tsx is pretty standard React 18+ bootstrap code.
How to integrate csrfTokenManager.init() in this setup?
Since your app rendering is synchronous, but csrfTokenManager.init() is async, you need to:
Wait for csrfTokenManager.init()before rendering the React root.
Then render your <App /> inside I18nextProvider and React.StrictMode as usual.
Make sure any failing in init is handled gracefully.
Modified src/index.tsx example with CSRF token init:
tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import reportWebVitals from './reportWebVitals.ts';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/i18n';
import App from './App';
import { csrfTokenManager } from './services/csrfServices'; // import your csrfTokenManager
const container = document.getElementById('root');
if (!container) {
throw new Error("Root element with id 'root' not found.");
}
const root = createRoot(container);
async function bootstrap() {
try {
// Await CSRF token manager initialization
await csrfTokenManager.init();
// Now render app normally
root.render(
<React.StrictMode>
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>
</React.StrictMode>
);
} catch (error) {
console.error('Failed to initialize CSRF tokens:', error);
// Optional: render an error UI, or retry logic here
}
}
// Call bootstrap to initialize and render app
bootstrap();
// Optional: Monitor performance metrics
reportWebVitals(console.log);
Explanation
The bootstrap async function does your async setup first.
After awaiting your CSRF token fetch/init, it renders the React app as normal.
This ensures all components load with valid CSRF tokens available.
Any API calls or forms rendered inside the app will find tokens ready.
Important notes
If you have other async initialization (e.g. user session, config), you can also chain them in bootstrap().
During development, you might want to show a loading spinner until bootstrap() finishes.
If init fails, you can show an error message or fallback UI for better UX.
If you want, I can also help you add a loading or error UI around this async bootstrap before rendering <App/> — just ask!
User
or would it be better todo this in the app?
// src/App.tsx
import React, { useEffect } from 'react';
import { BrowserRouter, Routes, Route, useLocation } from 'react-router';
import 'bootstrap/dist/css/bootstrap.min.css';// Import Bootstrap CSS
import 'bootstrap/dist/js/bootstrap.bundle.min.js';// Import Bootstrap JS, includes Popper.js
import 'bootstrap-icons/font/bootstrap-icons.css';// Bootstrap Icons
//import logo from './logo.svg';
import { csrfTokenManager } from './services/csrfServices';
import Main from './components/Main';
import Site from './components/Site';
useEffect(() => {
if (location.pathname.startsWith('/'))
{
// @url https://developer.mozilla.org/en-US/docs/Web/API/Document/body
document.body.classList.remove('app-background');
document.body.style.backgroundColor = 'var(--site-background-color)';
}
else
{
document.body.classList.add('app-background');
}
}, [location.pathname]);// Update effect on path change
return (
<Routes>
{/*
Site path:
You rendered descendant <Routes> (or called `useRoutes()`) at "/" (under <Route path="/">) but
the parent route path has no trailing "*". This means if you navigate deeper, the parent won't
match anymore and therefore the child routes will never render.
Please change the parent <Route path="/"> to <Route path="*">.
App path:
You rendered descendant <Routes> (or called `useRoutes()`) at "/app" (under <Route path="/app">) but
the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match
anymore and therefore the child routes will never render.
Please change the parent <Route path="/app"> to <Route path="/app/*">.
*/}
<Route index path="*" element={ <Site /> } />{/* Root path */}
<Route path="/app/*" element={ <Main /> } />
</Routes>
);
};
const App = () =>
{
return (
);
};
export default App;
Assistant
Great question! Both approaches — initializing CSRF tokens in index.tsx before rendering your app or inside your app component/runtime (App.tsx) — have pros and cons.
- Ensures CSRF token is definitely ready for any component.- No "loading" state inside app needed.- Simpler downstream logic, components assume token ready.
- Adds complexity to your bootstrap code.- Harder to show UI (spinner, etc) while loading.- If init() fails, you must handle rendering fallback outside the app.
Init inside App.tsx (in useEffect)
Initialize in a React component, e.g. top-level or AppContent useEffect.
- Easy to handle loading / error UI inside React render tree.- More idiomatic React pattern.- Allows partial app rendering even if async initialization takes time.
- Components that need CSRF tokens must handle them being initially undefined.- Possible race conditions if components try to use tokens before ready.- You must implement loading gating / token availability checks yourself.
How to implement it inside your App.tsx
If you want to initialize CSRF tokens inside App, you typically do:
tsx
User
import React from 'react';
import { createRoot } from 'react-dom/client';
import reportWebVitals from './reportWebVitals.ts';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/i18n';
import App from './App';
import { csrfTokenManager } from './services/csrfServices'; // import your csrfTokenManager
Yes, you can absolutely use a modern immediately-invoked async function expression (an async IIFE), which is a common and succinct way to write async bootstrap code in modern JavaScript/TypeScript.
logger.info('handleApiResponseWithState', 'Stored accessToken and refreshToken securely');
}
catch (error)
{
logger.error('handleApiResponseWithState', 'Failed to store tokens securely', error);
}
}
this causes a error.. but i cant see the error the react site goes blank white screen
Assistant
A blank white screen in React usually means your app has encountered an uncaught runtime error and crashed. Since you say your code involves await setAccessTokenNative(...) but you don’t see errors logged, likely there is an unhandled exception, or something is silently failing.
Debugging steps and things to check:
1. Confirm setAccessTokenNative and setRefreshTokenNative are async functions returning Promises
If these functions are not actually returning Promises (or not marked async), then doing:
ts
await setAccessTokenNative(...);
could cause a runtime error or unexpected behavior.
Are these functions your own? Are they wrappers around e.g. localStorage, AsyncStorage, or native APIs?
If they are synchronous, remove the await.
2. Use a try/catch around the entire block to catch unexpected errors
Sometimes errors happen outside the inner try/catch if await is used in the outer scope. Wrapping more tightly helps catch unexpected exceptions.
3. Check if setAccessTokenNative or setRefreshTokenNative throw synchronously or reject the Promise
If these functions throw synchronously (not return rejected Promise), your must wrap that synchronous code outside .
User
if (success && response.data)
{
// Confirm passing setStep to handleApiResponseWithState
if (typeof setStep === 'function')
{
// TODO - Removed for replacement of user_key that is set inside the JWT token of the cookie...
/if (typeof response.data.userId === 'string')
{
setUserId(response.data.userId);
}/
code
// If both nextStep and signupPhase are present, nextStep is used.
if (typeof response.data.nextPhase === 'number')
{
setStep(response.data.nextPhase);
logger.info('signupApiResponseWithState.ts', 'Using nextPhase:', response.data.nextPhase);
}
// If nextStep is missing or invalid, fallback to signupPhase.
else if (typeof response.data.signupPhase === 'number')
{
setStep(response.data.signupPhase);
logger.info('signupApiResponseWithState.ts', 'Using signupPhase:', response.data.signupPhase);
}
// If both missing, fallback to step 0.
else
{
// fallback/reset step
setStep(0);
logger.info('signupApiResponseWithState.ts', 'Fallback to phase zero');
}
}
/**
* TODO - Native React App
* Accessing and setting JWT tokens for Native React App support
*
* Note: Do NOT use localStorage or AsyncStorage alone for tokens in native apps — it’s not secure.
*
if (typeof response.data.accessToken === 'string' && typeof response.data.refreshToken === 'string')
{
try
{
await setAccessTokenNative(response.data.accessToken);
await setRefreshTokenNative(response.data.refreshToken);
logger.info('handleApiResponseWithState', 'Stored accessToken and refreshToken securely');
}
catch (error)
{
logger.error('handleApiResponseWithState', 'Failed to store tokens securely', error);
}
}//*/
}
A blank white screen usually means your React app hit a runtime error that crashed the rendering, and it wasn’t caught or logged visibly.
Your code snippet does asynchronous await calls inside a non-async function or inside synchronous code.
Most likely cause:
You are calling await setAccessTokenNative(...)inside a synchronous callback or function that is not async, so the error bubbles and crashes the app. React won't handle a rejected Promise inside a non-async handler gracefully.
How to fix this:
Make sure your surrounding function (the one containing await) is declared async.
For example, if inside a .then() or event handler, either:
Mark the function async
Or do the await inside an async function you call
Example:
ts
// Let's say your handler looks like this (synchronous):
function handleResponse(response, setStep) {
if (
response.data.accessToken && typeof response.data.accessToken === 'string' &&
response.data.refreshToken && typeof response.data.refreshToken === 'string'
) {
// This is sync function — await here will throw syntax error or runtime crash
await setAccessTokenNative(response.data.accessToken);
await setRefreshTokenNative(response.data.refreshToken);
}
}
// Fix:
async function handleResponse(response, setStep) {
if (
response.data.accessToken && typeof response.data.accessToken === 'string' &&
response.data.refreshToken && typeof response.data.refreshToken === 'string'
) {
try {
await setAccessTokenNative(response.data.accessToken);
await setRefreshTokenNative(response.data.refreshToken);
} catch (error) {
logger.error('handleApiResponseWithState', 'Failed to store tokens securely', error);
}
}
}
User
import React from 'react';
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
/**
* React Strict Mode in Development
* If your React app is wrapped in <React.StrictMode>, React intentionally mounts
* components twice (only in development) to help detect side effects and bugs. This causes
* effects like useEffect to run twice, which can lead to duplicate fetches.
*
* Render App wrapped with I18nextProvider
*/
root.render(
<React.StrictMode>
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>
</React.StrictMode>
);
}
catch (error)
{
console.error('Failed to initialize CSRF tokens:', error);
// Optionally render error UI or retry logic here
}
})();
// Optional: Report web vitals (for performance measuring)
reportWebVitals(console.log);
Assistant
Thanks for sharing your ErrorBoundary and index.tsx setup. Your approach is mostly correct and the ErrorBoundary should catch render errors within the React tree, but it cannot catch errors thrown before React rendering starts, such as in your async IIFE in index.tsx.
Why your ErrorBoundary might not catch some errors
The async IIFE that calls await csrfTokenManager.init() runs outside React’s rendering system.
If csrfTokenManager.init() throws or rejects, the error is caught in your catch block inside the IIFE — but you currently only log to console and do not render any UI for that error.
Since root.render() is not called on error, React tree (and therefore ErrorBoundary) never mounts — so nothing renders, causing a blank page.
Even React.StrictMode doesn't affect this behavior: errors thrown before React root rendering cannot be caught by React.
How to fix this so users see a meaningful error UI
You have two main options:
Option 1: Render an error fallback UI on CSRF init failure outside React tree
Modify your catch block in index.tsx to render a minimal React tree with an error message (or your ErrorBoundary + fallback), rather than just console logging:
tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
// ...other imports
import ErrorBoundary from './components/ErrorBoundary'; // your ErrorBoundary component or inline it
const container = document.getElementById('root');
if (!container) {
throw new Error("Root element with id 'root' not found.");
}
const root = createRoot(container);
(async () => {
try {
await csrfTokenManager.init();
root.render(
<React.StrictMode>
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>
</React.StrictMode>
);
} catch (error) {
console.error('Failed to initialize CSRF tokens:', error);
// Render error UI instead of blank screen
root.render(
<React.StrictMode>
<ErrorBoundary>
<div style={{ padding: 20, color: 'red' }}>
Failed to initialize app: {error instanceof Error ? error.message : String(error)}
</div>
</ErrorBoundary>
</React.StrictMode>
);
}
})();
User
give me option 2
Assistant
Certainly! Here's a full example implementing Option 2, where the CSRF token initialization happens inside your React app, enabling you to show loading and error states within React's rendering lifecycle:
1. Create AppWrapper.tsx
This component will handle CSRF token initialization before rendering your main App.
tsx
// src/AppWrapper.tsx
import React, { useState, useEffect } from 'react';
import { csrfTokenManager } from './services/csrfServices';
import App from './App';
const AppWrapper: React.FC = () => {
const [loading, setLoading] = useState(true);
const [initError, setInitError] = useState<Error | null>(null);
useEffect(() => {
csrfTokenManager.init()
.then(() => setLoading(false))
.catch(error => {
setInitError(error instanceof Error ? error : new Error(String(error)));
setLoading(false);
});
}, []);
if (loading) {
return <div>Loading security tokens...</div>;
}
if (initError) {
return (
<div style={{ color: 'red', padding: 20 }}>
Failed to initialize security tokens: {initError.message}
</div>
);
}
// When CSRF initialization is done and successful, render the main app
return <App />;
};
export default AppWrapper;
2. Modify src/index.tsx to render AppWrapper immediately
You no longer need to await initialization here; just render the wrapper:
tsx
User
instead of setting up the csrfTokenManger in the app like this:
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { csrfTokenManager } from './services/csrfServices';
import Main from './components/Main';
import Site from './components/Site';
const AppContent = () => {
// State to track if CSRF is ready
const [csrfReady, setCsrfReady] = useState(false);
const [csrfError, setCsrfError] = useState<Error | null>(null);
if (csrfError) {
return Error initializing CSRF Token: {csrfError.message};
}
if (!csrfReady) {
return Loading security tokens...;
}
// Render your routes normally once CSRF token is ready
return (
<Route path="/" element={} />
<Route path="/app/" element={} />
);
};
const App = () => (
);
export default App;
could i do it in the site.tsx?
// src/components/Site.tsx
import React, { useEffect, useRef } from 'react';
import { Routes, Route } from 'react-router';
import { AlertProvider, useAlert } from '../hooks/useAlertHooks';
import { useEventListener } from '../hooks/useEventListenerHooks';
import { csrfTokenManager } from './services/csrfServices';
import '../styles/Site.css';
import Header from './site/Header';
import Content from './site/Content';
import Footer from './site/Footer';
import Faq from './site/Faq';
import Login from './site/Login';
import Signup from './site/Signup';
const SiteContent = () =>
{
// Get showAlert function from context
const { showAlert, dismissAlert, alerts } = useAlert();
code
Assistant
Yes, you can absolutely move the CSRF token initialization logic into your Site (or anywhere deeper in your component tree), and use your existing alert system to display errors or loading states. This can work well if:
The rest of your app (like Main or other routes) do not require the CSRF token immediately.
You want to localize the loading and error UI inside the Site component/UI.
You want to unify UX using your showAlert mechanism for any CSRF initialization failures.
How you could do it in SiteContent
Here's how to adapt your SiteContent to initialize the CSRF token and use your alert system for error/loading UI:
tsx
User
import React, { useEffect, useRef, useState } from 'react';
import { Routes, Route } from 'react-router';
import { AlertProvider, useAlert } from '../hooks/useAlertHooks';
import { useEventListener } from '../hooks/useEventListenerHooks';
import { csrfTokenManager } from '../services/csrfServices'; // fix import path
Got it! If you want to only show the error message when there is an error, but otherwise show the normal routes regardless of whether CSRF is ready or not, you can simplify your rendering like this:
Let me know if you want help handling cases when CSRF token is actually required and not ready — for example disabling some buttons or blocking API calls until ready!
User
// Local state indicating if CSRF initialization completed successfully
const [csrfReady, setCsrfReady] = useState(false);
code
// Local state holding any error encountered during CSRF initialization
const [csrfError, setCsrfError] = useState<Error | null>(null);
// Run this effect once on component mount to initialize CSRF token manager
useEffect(() =>
{
csrfTokenManager.init().then(() => setCsrfReady(true)).catch(error =>
{
// Save error state for error UI rendering
setCsrfError(error instanceof Error ? error : new Error(String(error)));
// Show alert for error using your alert system
const id = showAlert(
'danger',
`Failed to initialize security tokens: ${error instanceof Error ? error.message : String(error)}`
);
// Store alert ID so we can dismiss it on cleanup
alertIds.current.push(id);
});
}, [showAlert]);
remove the csrfReady and setCsrfReady code now since i dont need it
Assistant
Sure! Since you no longer need to track or display a separate loading state (csrfReady), you can remove the related state and just keep the error handling and alert logic. Your updated code would look like this:
tsx
// Remove these lines:
// const [csrfReady, setCsrfReady] = useState(false);
const [csrfError, setCsrfError] = useState<Error | null>(null);
useEffect(() => {
csrfTokenManager.init()
.catch(error => {
// Save error state to optionally display error UI
setCsrfError(error instanceof Error ? error : new Error(String(error)));
// Show alert for error using your alert system
const id = showAlert(
'danger',
`Failed to initialize security tokens: ${error instanceof Error ? error.message : String(error)}`
);
// Store alert ID so we can dismiss it on cleanup
alertIds.current.push(id);
});
}, [showAlert]);
Summary of changes:
Removed the csrfReady state and setCsrfReady(true) call.
The effect init now just runs and handles errors.
You still set the error into csrfError state so you can handle error UI if you want.
The main app renders immediately, regardless of whether the CSRF token is ready.
If you don't want to render any loading UI or care about readiness, this is the minimal setup for CSRF token initialization with error alerting.
Let me know if you want me to help with the relevant rendering logic (e.g. just error message or just routes).
User
nativeTokenStorageServices.ts:51 nativeTokenStorage: getAccessToken called
hook.js:608 (2025-05-24T01:59:59.723Z) [apiClientServices.ts] Unhandled error: AxiosError
overrideMethod @ hook.js:608Understand this warning
hook.js:608 (2025-05-24T01:59:59.725Z) [useSignup.ts] Failed to fetch business categories: AxiosError
overrideMethod @ hook.js:608Understand this warning
hook.js:608 (2025-05-24T01:59:59.725Z) [useSignup.ts] Failed to fetch business categories: AxiosError
overrideMethod @ hook.js:608Understand this warning
hook.js:608 (2025-05-24T01:59:59.726Z) [apiClientServices.ts] Unhandled error: AxiosError
overrideMethod @ hook.js:608Understand this warning
hook.js:608 (2025-05-24T01:59:59.726Z) [csrfServices.ts] Failed to fetch CSRF tokens during init: AxiosError
overrideMethod @ hook.js:608Understand this warning
loggerUtils.ts:151 (2025-05-24T01:59:59.726Z) [csrfServices.ts] Cookie _csrf value: undefined
Does not appear to display the csrf error if: Failed to initialize security tokens
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your frontend app initialization code (e.g. top-level entry
or React app startup):
import { csrfTokenManager } from './services/csrfServices';
async function bootstrapApp()
{
code
await csrfTokenManager.init();
code
// ... continue app startup
}
bootstrapApp();
Set up Axios interceptor to add CSRF header automatically
import apiClient from './services/apiClientServices';
import { csrfTokenManager } from './services/csrfServices';
apiClient.interceptors.request.use(config =>
{
code
const token = csrfTokenManager.getRawToken();
code
if (token)
code
{
Assistant
The main reason your CSRF init error is not displaying properly despite the Axios error and cookie being undefined is because in your CsrfTokenManager.init method, the catch block only logs the error but does not propagate it or set any visible error state.
Key reasons why error UI does not show:
init() swallows the error by catching and only logging it:
ts
async init(): Promise<void> {
if (this.initPromise) return this.initPromise;
this.initPromise = (async () => {
try {
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
} catch (error) {
logger.warn('csrfServices.ts', 'Failed to fetch CSRF tokens during init:', error);
// <-- error logged but NOT re-thrown or exposed
}
// read signed cookie token regardless
this.csrfCookieToken = getSignedCsrfTokenFromCookie();
})();
return this.initPromise;
}
So when you call csrfTokenManager.init() in React:
The .catchnever runs, because init() does not reject the promise on failure. The promise resolves anyway.
What to do?
To propagate errors properly so your React component receives and can handle them, you must re-throw in the catch inside init().
Update init() like so:
ts
User
adding "throw error" caused:
Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. public.6efbc4f8.js:34414:18
Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. public.6efbc4f8.js:34414:18
XHRPOST
http://localhost:1234/__parcel_code_frame
NS_BINDING_ABORTED
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource. public.6efbc4f8.js:34360:21
Could not get the stack frames of error: TypeError: NetworkError when attempting to fetch resource.
almost crashed my deve server
Assistant
The "Maximum update depth exceeded" error usually means your React component is stuck in an infinite render loop caused by state updates triggering repeated effects.
In your case, adding throw error inside the init() triggers the error to be caught in your component's useEffect where you call:
Cause: showAlert function is not stable and triggers effect repeatedly
If showAlert is recreated on every render (not memoized), then [showAlert] changes every render.
This causes the useEffect to rerun infinitely, calling init() repeatedly, calling setCsrfError repeatedly, and causing React to throw max update depth.
How to fix:
Make sure showAlert is stable (memoized or referentially stable).
Or remove or adjust useEffect dependency array carefully:
Usually for external functions from context/hooks, it's safe to omit them from dependencies if you know they won't change during your component lifetime:
Add a comment disabling exhaustive deps linting only if you are sure showAlert won't change.
Alternative: use a wrapper stable callback
If you want to include showAlert safely, you can use useCallback or similar pattern inside your alert hook/provider to guarantee stable function references.
Important:
User
rror: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
▶ 5 stack frames were collapsed.
(anonymous function)
src/components/Site.tsx:33:3
30 | csrfTokenManager.init().catch(error =>
31 | {
32 | // Save error state for error UI rendering
33 | setCsrfError(error instanceof Error ? error : new Error(String(erro
| ^
34 |
35 | // Show alert for error using your alert s
Assistant
The "Maximum update depth exceeded" caused by this snippet:
means something inside this effect triggers repeated renders, usually because:
setCsrfError updates state that causes the component to rerender,
And eithershowAlert or some other prop/function in scope causes the effect to rerun because of changing dependencies,
Or your useEffect dependencies are incorrect or omitted.
Why does this happen?
useEffect runs once at mount because dependencies array is empty, but the error you set in state via setCsrfError triggers a re-render.
That should be okay, so the likely culprit is that the component rerenders, and either the showAlert function or some other part used in the effect is unstable and recreated on every render.
If you include such unstable items in the dependencies array, the effect fires again, causing infinite updates.
How to fix this (step-by-step):
Step 1: Make sure your useEffect dependencies are correct and minimal
You want the effect to run once on mount only. Usually, this means an empty array ([]).
But you are using showAlert, which you got from a hook (useAlert()), which might produce a new function reference each render if not memoized.
Solution A: Ignore (with comment) or memoize showAlert in the hook provider.
tsx
User
is using "throw error" the best option? and useCallback on this?
1. Is using throw error in your init() method the best option?
Short answer:
Yes, throwing is a good practice to propagate errors up, allowing your UI or higher-level handlers to react properly to failures.
Why?
If you swallow the error (i.e., catch it but don’t re-throw), the caller (your React component) cannot know initialization failed.
By throwing the error, your init() method returns a rejected Promise when something goes wrong.
Your React component’s catch block will then run, enabling you to show alerts or error UI.
Otherwise, the component assumes success even if init failed.
However, you should be aware that:
If you throw and your React effect is not carefully coded, you can cause infinite re-renders (see earlier discussion).
So handling throw properly requires a stable useEffect and memoized functions, or ignoring functions from dependencies with comments (// eslint-disable).
Conclusion: Throw the error in init() to propagate it, and fix useEffect to avoid infinite loops (memoize alert functions or omit them from deps).
2. Should you memoize handleAlert using useCallback?
If you’re passing handleAlert as a dependency to a hook (like your useEventListener), and especially if useEventListener uses it as a dependency or adds/removes listeners depending on it, then yes, memoizing with is recommended.
Cleanup function to dismiss all alerts you previously raised to avoid leaving them displayed when component unmounts.
When might you skip it?
If your alert system automatically dismisses alerts after a timeout and you don’t need to manually dismiss on unmount.
If alerts are global and unrelated to this specific component lifecycle.
If you want alerts to persist across app navigation.
Recommendation for your case
Since you're showing CSRF init error alerts via showAlert in useEffect, keeping alertIds and cleanup ensures:
Alerts created here get dismissed when the component is removed.
Keeps UI clean and prevents old alerts from filling the screen.
Prevents unexpected behavior if the component unmounts/remounts.
Summary:
Keep alertIds + cleanup?
Reason
Yes
You want to cleanly manage alerts lifecycle tied to component lifecycle
No
Your alert system handles automatic dismissal or you want alerts to survive navigation
Final note:
If your alerts naturally dismiss after a short period (e.g. 3-5 seconds), cleanup on unmount is less critical, but still good practice to avoid UI consistency issues.
If you want, I can help optimize your alerts lifecycle further or help implement timeouts and auto-dismiss!
// Use the AlertContext in any component
export const useAlert = () =>
{
// React - useContext. Retrieves the current context value from the nearest Provider.
const context = useContext(AlertContext);
code
if (!context)
{
throw new Error('useAlert must be used within an AlertProvider');
}
return context;
AlertProvider component that wraps the application to provide alert functionality
React - ReactNode. Type that represents anything renderable in React
(elements, strings, arrays, etc.).
*/
export const AlertProvider = ({ children }: AlertProviderProps) =>
{
// React - useState. Adds state to a functional component; returns current state and a setter function.
const [alerts, setAlerts] = useState<Alert[]>([]);
showAlert function: Adds a new alert message to the alert state.
@param {string} type - The type of alert (success, error, info, etc.).
Assistant
The error message:
code
Encountered two children with the same key, `1748052589701`. Keys should be unique so that components maintain their identity across updates...
means you are rendering React elements with duplicate keys. React keys must be unique among siblings to help React’s reconciliation algorithm.
Why is this happening in your code?
Looking at your showAlert implementation:
ts
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const id = Date.now(); // Unique ID for the alert
...
setAlerts(prevAlerts => [...prevAlerts, { id, type: alertClass, message }]);
...
return id;
};
You're generating alert ids using Date.now(). This is not guaranteed unique if you call showAlert multiple times in the same millisecond.
How to fix keys uniqueness?
Option 1: Use a better unique ID generator
Use a sequential incrementing ID variable or a library like nanoid or uuid.
Example with a simple incremental counter:
ts
let alertIdCounter = 0;
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const id = ++alertIdCounter; // incrementing ID guarantees uniqueness during runtime
setAlerts(prev => [...prev, { id, type: alertClass, message }]);
// rest unchanged...
return id;
};
Option 2: Use libraries for unique IDs
Install nanoid (small and fast):
bash
npm install nanoid
Then:
ts
User
let alertIdCounter = 0;
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const id = ++alertIdCounter; // incrementing ID guarantees uniqueness during runtime
setAlerts(prev => [...prev, { id, type: alertClass, message }]);
// rest unchanged...
return id;
};
could I do this with the time? so adding a digiit?
Assistant
Yes! You can combine the timestamp with an incrementing digit/counter to create a more unique id, reducing the chance of collisions when multiple alerts happen within the same millisecond.
Simple approach combining time + incrementing counter
ts
let alertCounter = 0;
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const now = Date.now();
alertCounter = (alertCounter + 1) % 1000; // wrap at 1000 to keep numbers reasonable
// Combine time and counter to create a unique-ish ID
// Multiply timestamp by 1000 and add counter to distinguish alerts fired in the same ms
const id = now * 1000 + alertCounter;
setAlerts(prev => [...prev, { id, type: alertClass, message }]);
if (duration !== null) {
setTimeout(() => dismissAlert(id), duration);
}
return id;
};
Explanation
Date.now() gives the timestamp in milliseconds.
You multiply by 1000 to create space for the alertCounter (0–999).
alertCounter increments for each alert fired in the same millisecond.
The resulting id will be unique for as many as 1000 alerts per millisecond (much more than realistic).
Notes
This is still not cryptographically guaranteed, but perfectly fine for UI keys.
Using a small integer counter appended to timestamp is a common simple way to get unique IDs.
It stays numeric which is often convenient.
Alternative: string IDs
If you want to avoid number tricks, you could also do:
ts
const id = `${Date.now()}-${alertCounter}`;
and change your Alert interface id to string.
Summary
Combining timestamp + counter is a neat pragmatic way to produce unique numeric alert IDs and avoid React key collisions without pulling external libraries.
If you want, I can help refactor your full alert hook with this approach!
User
or any better ideas, but not installing another package
Assistant
If you want to avoid installing an external package and still generate unique IDs that are reliable for your alert system, here are some good approaches you can safely use:
1. Timestamp + Incrementing Counter (Numeric IDs)
As you suggested, this is a very practical approach.
Example:
ts
let alertCounter = 0;
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const now = Date.now();
alertCounter = (alertCounter + 1) % 1000; // Wrap to avoid large numbers
const id = now * 1000 + alertCounter; // Combines time + counter, creates unique numeric ID
setAlerts(prev => [...prev, { id, type: alertClass, message }]);
if (duration !== null) {
setTimeout(() => dismissAlert(id), duration);
}
return id;
};
Why is this good?
Very unlikely to collide — multiple alerts created within the same millisecond get unique IDs due to the counter.
Numeric ID, easy to use as React keys.
No third-party dependencies.
No risk of repeating IDs across re-renders/on reload (but they don't need to be stable beyond runtime).
2. Simple Increasing Counter Only
If you think you won't create alerts simultaneously (within the same millisecond), a simple global incrementing counter can suffice:
ts
let alertIdCounter = 0;
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number => {
const id = ++alertIdCounter;
setAlerts(prev => [...prev, { id, type: alertClass, message }]);
if (duration !== null) {
setTimeout(() => dismissAlert(id), duration);
}
return id;
};
Pros:
Easy to implement.
Always unique within app lifetime.
Cons:
User
why does this error: Failed to initialize security tokens appear more than once
Assistant
The error message "Failed to initialize security tokens" appearing multiple times usually means your error handling code (the alert display logic) is being executed repeatedly. This commonly happens because the component or effect responsible for initialization and error reporting runs more than once, causing multiple alerts to be shown.
Here are the most common causes and how to address them:
1. Effect runs multiple times due to dependencies / Strict Mode
And showAlert is a function that changes on every render (not memoized), the dependency on showAlert causes this effect to rerun continuously.
Or if your app runs in React.StrictMode (development only), React deliberately mounts, unmounts, and remounts components to help detect side effects — causing effects to run twice.
How to fix:
Memoize showAlert in your alert context/provider using useCallback so it’s stable.
Or remove/ignore showAlert from dependency array of useEffect if you know it does not change:
2. No guard making sure initialization happens exactly once
If somehow your component unmounts and remounts repeatedly, it will call init() multiple times, leading to multiple errors if init fails.
How to fix:
Ensure csrfTokenManager.init() is only called , for example by calling it once in your app root or wrapping component.
Not yet included in a published release.
public function beforeAction($action): bool
{
if (in_array($action->id, ['csrf-token', 'refresh-jwt-token', 'submit-form']))
{
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
/**
* Axios is configured properly on frontend to send cookies and headers
* Must set { withCredentials: true } in Axios config to send cookies cross-site.
* Add the CSRF token header from cookie or from your actionCsrfToken API, e.g.:
*
* import Cookies from 'js-cookie';
*
* const csrfToken = Cookies.get('csrfToken'); // cookie name = 'csrfToken'
* axios.defaults.withCredentials = true;
* axios.defaults.headers.common['X-CSRF-Token'] = csrfToken;
* // Alternatively, fetch token from API and set header dynamically
*/
public function actionCsrfToken(): array
{
$request = \Yii::$app->request;
if (!$request->isGet)
{
throw new BadRequestHttpException('Only GET requests are allowed.');
}
$token = $request->getCsrfToken();
\Yii::debug('CSRF Token from getCsrfToken(): ' . $token, __METHOD__);
/**
* Explicitly add CSRF cookie to response (forces Set-Cookie header)
* Note: Setting cookie for CSRF token is handled by Yii
*
$response->cookies->add(
new Cookie([
//'name' => $request->csrfParam,// This would use '_csrf'
'name' => 'csrfToken',
'value' => $token,
'httpOnly' => false,// Always false for csrf token
'secure' => YII_ENV_PROD ? true : false,// True if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
'path' => '/',// Ensure cookie always overrides previous cookies on all paths
])
);//*/
$response = \Yii::$app->response;
//\Yii::debug("CSRF token to send to client: $token", __METHOD__);
//\Yii::debug('Sending CSRF cookie with params: ' . json_encode($response->cookies->toArray()), __METHOD__);
// No need to set format here explicitly if contentNegotiator behavior is active,
//\Yii::$app->response->format = Response::FORMAT_JSON;
\Yii::$app->response->statusCode = 200;
/**
* Return the raw CSRF token in JSON for frontend use.
* - The CSRF cookie sent to the client is signed and serialized by Yii for security,
* so its value is NOT the raw token string and cannot be reliably read or used by JavaScript.
* - The frontend needs the raw CSRF token string to include in request headers (e.g., 'X-CSRF-Token')
* or POST parameters to comply with Yii's CSRF validation mechanism.
* - Returning the raw token via JSON allows the frontend to securely obtain the usable token
* without parsing or trusting the signed cookie.
* - The signed cookie enforces token integrity and ties the token to the user's session,
* while the raw token from JSON is the secret value the client must send back for validation.
*
* Example for typical usage flow
*
* // At app start
* await csrfTokenManager.init();
*
* // When sending API request or submitting form:
* const token = csrfTokenManager.getToken();
*
* apiClient.post('/user/update', formData, {
* headers: {
* 'X-CSRF-Token': token
* }
* });
*
* Or, if submitting a form traditionally:
*
* <input type="hidden" name="_csrf" value="TOKEN_FROM_BACKEND_JSON" />
*/
return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];
}
class CsrfTokenManager
{
private csrfParam?: string;
private csrfToken?: string; // raw token from backend JSON response, for header
private csrfCookieToken?: string; // signed cookie string from cookie, read-only
private initPromise?: Promise<void>;
async init(): Promise<void>
{
if (this.initPromise)
{
return this.initPromise;
}
this.initPromise = (async () => {
try {
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam; // e.g. '_csrf'
this.csrfToken = csrfToken; // raw backend token (for header)
}
catch (error) {
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Read **cookie token separately** but don't overwrite raw token:
this.csrfCookieToken = getSignedCsrfTokenFromCookie();
})();
return this.initPromise;
}
/**
* Get the raw CSRF token string from backend JSON.
* This is the token to put in `X-CSRF-Token` header.
*/
getRawToken(): string | undefined
{
return this.csrfToken;
}
/**
* Get the signed CSRF token string read from cookie.
* Usually NOT needed for manual use.
*/
getCookieToken(): string | undefined
{
return this.csrfCookieToken;
}
/**
* Get the CSRF parameter name (usually '_csrf'), useful for form hidden inputs.
*/
getParam(): string | undefined
{
return this.csrfParam;
}
}
// Function to read the signed CSRF cookie value (not raw token)
export function getSignedCsrfTokenFromCookie(): string | undefined
{
logger.log('All cookies via js-cookie:', Cookies.get(CSRF_COOKIE_NAME));
return Cookies.get(CSRF_COOKIE_NAME);
}
export const csrfTokenManager = new CsrfTokenManager();
Adapt fetchCsrfToken() function as:
fetch backend JSON: { csrfParam, csrfToken } where csrfToken is raw token string
After waiting for 50ms (to ensure cookie arrival), read cookie token (signed string)
Don't compare or expect cookie to equal raw token string (they won't)
Return raw token + param to caller
ts
export async function fetchCsrfToken(): Promise<CsrfData>
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
// Wait briefly to allow cookie to be set by backend
await new Promise(resolve => setTimeout(resolve, 50));
const cookieToken = getSignedCsrfTokenFromCookie();
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
// Log tokens - note these are different formats/values, that's expected
logger.log('csrfServices.ts', 'Token from backend response (raw):', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie (signed):', cookieToken);
return { csrfParam, csrfToken };
}
How to Use These Tokens in Axios
In your axios interceptor:
ts
import { csrfTokenManager } from './csrfServices';
apiClient.interceptors.request.use(config =>
{
// Use **raw token** from backend JSON for header X-CSRF-Token
const token = csrfTokenManager.getRawToken();
if (token)
{
config.headers['X-CSRF-Token'] = token;
}
// withCredentials must be true elsewhere in axios config, so cookie is sent automatically
return config;
});
Why?
Yii expects X-CSRF-Token header to have the raw (unsigend) token string.
Browser sends the signed cookie automatically.
Backend validates that header token matches the cookie & session.
Reading the cookie value in frontend is mostly for info/debug; since it’s signed, you cannot directly compare or use it for requests.
Summary
Token
Use case
Source
Usage on frontend
Raw CSRF token
Add to X-CSRF-Token header for API requests
Backend JSON from /csrf-token
Cache it, send it in headers
Signed CSRF cookie token
Cookie sent automatically by browser
Cookie _csrf or csrfToken
Read-only, for debug or info
Final notes
Make sure axios withCredentials is enabled to send cookies on cross-origin requests.
Don’t try to synchronize or compare raw token and cookie token in frontend; accept they differ.
For form submissions, use raw token in hidden input field.
For ajax/API, use raw token in header.
If you want, I can help you rewrite your entire csrfServices.ts file accordingly! Just let me know.
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
export const CSRF_COOKIE_NAME = '_csrf'; // or 'csrfToken' depending on your backend cookie name
export interface CsrfData {
csrfParam: string; // e.g. '_csrf'
csrfToken: string; // raw CSRF token string from backend JSON response
}
/**
* Fetch CSRF token and parameter from backend JSON API.
* Backend also sets signed CSRF cookie separately.
*
* Throws error if data missing or cookie absent.
*/
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token from backend response.');
}
// Wait briefly to ensure cookie is set by backend (important)
await new Promise(resolve => setTimeout(resolve, 50));
const cookieToken = getSignedCsrfTokenFromCookie();
if (!cookieToken) {
throw new Error('CSRF token cookie missing after fetching token.');
}
logger.log('csrfServices.ts', 'Raw token (backend JSON):', csrfToken);
logger.log('csrfServices.ts', 'Signed token (cookie):', cookieToken);
return { csrfParam, csrfToken };
}
/**
* Read the signed CSRF token from browser cookie.
* This is a signed and serialized value, not raw token!
*/
export function getSignedCsrfTokenFromCookie(): string | undefined {
const cookieValue = Cookies.get(CSRF_COOKIE_NAME);
logger.log('csrfServices.ts', `Cookie ${CSRF_COOKIE_NAME} value:`, cookieValue);
return cookieValue;
}
/**
* Clear old CSRF cookie (optional, e.g. used if you refresh token)
*/
export async function clearCsrfCookie(): Promise<void> {
Cookies.remove(CSRF_COOKIE_NAME, { path: '/' });
}
/**
* CSRF Token Manager - singleton class instance.
* Handles fetching, caching, and providing raw token & cookie.
*/
class CsrfTokenManager {
private csrfParam?: string;
private csrfToken?: string; // Raw token from backend JSON (for headers)
private csrfCookieToken?: string; // Signed token from cookie (read-only)
private initPromise?: Promise<void>;
/**
* Initialize by fetching CSRF token from backend and reading cookie token.
* Must be called once on app startup, e.g. `await csrfTokenManager.init()`.
*/
async init(): Promise<void> {
if (this.initPromise) {
return this.initPromise;
}
this.initPromise = (async () => {
try {
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
} catch (error) {
logger.warn('csrfServices.ts', 'Failed to fetch CSRF tokens during init:', error);
}
// Always read the signed cookie token fresh
this.csrfCookieToken = getSignedCsrfTokenFromCookie();
})();
return this.initPromise;
}
/**
* Get the raw CSRF token (backend JSON) used for API request header `X-CSRF-Token`.
*/
getRawToken(): string | undefined {
return this.csrfToken;
}
/**
* Get the signed CSRF token value read from cookie.
* Usually unnecessary for API requests, but available if needed.
*/
getCookieToken(): string | undefined {
return this.csrfCookieToken;
}
/**
* Get CSRF param name (usually '_csrf', needed for form hidden inputs).
*/
getParam(): string | undefined {
return this.csrfParam;
}
/**
* Optional manual setter, e.g. if you want to manually update tokens.
*/
setTokens(rawToken?: string, param?: string, cookieToken?: string): void {
if (rawToken) this.csrfToken = rawToken;
if (param) this.csrfParam = param;
if (cookieToken) this.csrfCookieToken = cookieToken;
}
}
/**
* Singleton instance of the CSRF token manager
*/
export const csrfTokenManager = new CsrfTokenManager();
Usage Example
In your frontend app initialization code (e.g. top-level entry or React app startup):
ts
import { csrfTokenManager } from './services/csrfServices';
async function bootstrapApp() {
await csrfTokenManager.init();
// ... continue app startup
}
bootstrapApp();
Set up Axios interceptor to add CSRF header automatically
Choose either undefined or null for your “empty” initial state and be consistent.
Use proper nullish checks before using the value.
Prefer narrow and explicit types (e.g. string | undefined or string | null) rather than any.
Avoid mixing both unless you have a clear purpose.
Summary
Goal
Use null?
Use undefined?
Explicit empty state
Good choice
Also good, more common
Prevent runtime errors
No, checking logic is needed in both cases
Default uninitialized
Needs explicit assign
Default in JS/TS
General recommendation
Pick one and check for it consistently
If you want maximum safety, I'd recommend:
tsx
const [csrf, setCsrf] = useState<string | undefined>(undefined);
// later use
if (csrf != null) {
// safe to use csrf as string here
}
That’s idiomatic and straightforward for React + TypeScript.
Let me know if you want examples for safe usage patterns!
When this component renders, the manager’s tokens may or may not yet be set.
So calling getRawToken() & getParam() synchronously may return undefined initially.
useEffect runs after mount, so ensures boolean values stabilize.
Updating state triggers re-render with token present.
This keeps the form in sync with latest token values.
Alternative: if your app guarantees tokens are ready before rendering forms (e.g. csrfTokenManager.init() awaited on app start), you can also:
tsx
// Synchronously get token if app startup already done
const csrfToken = csrfTokenManager.getRawToken();
const csrfParam = csrfTokenManager.getParam();
and use directly if not undefined, skipping state + useEffect.
Bonus: If you want reactive updates if tokens refresh dynamically
tsx
useEffect(() => {
function updateTokens() {
setCsrfToken(csrfTokenManager.getRawToken());
setCsrfParam(csrfTokenManager.getParam());
}
updateTokens();
// Optionally subscribe to some token refresh event in your CSRF manager if you implement it
// Return unsubscribe function on cleanup
}, []);
Summary
Step
What to do
Get token for forms
Use CSRF token raw value from backend JSON
Access it in React
From csrfTokenManager.getRawToken() and .getParam()
src/services/csrfServices.ts — exports csrfTokenManager and helper functions.
Your app entry (e.g. src/index.tsx) imports and calls await csrfTokenManager.init()before rendering React app.
Your API client config uses csrfTokenManager.getRawToken() to set headers.
Minimal example app entry – React + csrfTokenManager
ts
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { csrfTokenManager } from './services/csrfServices';
async function bootstrapApp() {
try {
await csrfTokenManager.init();
ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
} catch (error) {
console.error('CSRF init failed:', error);
// fallback UI or retry logic here
}
}
bootstrapApp();
Why do this await csrfTokenManager.init()?
You want the CSRF tokens fully cached before any API call or form submission happens.
Avoid crazy bugs where initial API requests lack CSRF tokens and get rejected.
Since token fetching is async, waiting on init keeps your app predictable.
Summary
Step
What to do
Import CSRF token manager
import { csrfTokenManager } from './services/csrfServices';
Initialize at app startup
await csrfTokenManager.init();
Use token for API requests
csrfTokenManager.getRawToken()
Set token in forms hidden input
csrfTokenManager.getParam() and .getRawToken()
If you want, I can provide a complete minimal reproducible project example with this setup — just ask!
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { csrfTokenManager } from './services/csrfServices';
import Main from './components/Main';
import Site from './components/Site';
const AppContent = () => {
// State to track if CSRF is ready
const [csrfReady, setCsrfReady] = useState(false);
const [csrfError, setCsrfError] = useState<Error | null>(null);
// Initialize csrf token on component mount
useEffect(() => {
csrfTokenManager.init()
.then(() => setCsrfReady(true))
.catch((error) => {
setCsrfError(error);
console.error('CSRF token init failed:', error);
});
}, []);
if (csrfError) {
return <div>Error initializing CSRF Token: {csrfError.message}</div>;
}
if (!csrfReady) {
return <div>Loading security tokens...</div>;
}
// Render your routes normally once CSRF token is ready
return (
<Routes>
<Route path="/*" element={<Site />} />
<Route path="/app/*" element={<Main />} />
</Routes>
);
};
const App = () => (
<BrowserRouter>
<AppContent />
</BrowserRouter>
);
export default App;
Explanation
You display a loading message or spinner while csrfTokenManager.init() runs.
On error, show an error message.
Once ready, render your routes and components.
Components downstream can use csrfTokenManager.getRawToken() safely because it’s guaranteed initialized.
When to choose which?
Use index.tsx bootstrap init if you want to avoid any app render until CSRF is guaranteed ready and want minimal in-app loading states.
Use App.tsx init if you want flexible loading/error display inside React UI tree or want to integrate CSRF init with other app bootstrap logic (auth, config loading, etc).
Summary
Tasks required if you init in App.tsx
1. Add state for CSRF ready / error
2. Run csrfTokenManager.init() inside useEffect
3. Render loading UI while waiting
4. Render error UI if init fails
5. Render app routes only after init success
If you want, I can help you refactor your full App.tsx (including your route setup and body class logic) with proper CSRF loading handling incorporated. Just ask!
try/catch
await
4. Add more console logs before and after awaits to isolate exactly where the crash happens
Sometimes React hides the error in UI but it will be logged in DevTools console.
You can also enable error boundaries or React DevTools Profiler to get more insight.
6. Consider that setAccessTokenNative or setRefreshTokenNative might be using native APIs (e.g. React Native SecureStore)
Make sure those calls complete successfully, and your app has the right permissions or setup.
If you are on web and using localStorage (which is synchronous), do notawait them — they should be called synchronously.
7. If you are in React 18+ and using StrictMode, be aware that double mounting can cause double calls — but this causes warnings, not white screens usually.
Summary example with comprehensive catching and logs
Let me know if you want me to review the full method you put this code in!
This way, if your CSRF token setup fails, users see a message instead of a blank screen.
Option 2: Move CSRF initialization inside React app tree with loading/error UI
Instead of awaiting CSRF init before rendering, render React app immediately and do CSRF init inside, e.g., in App.tsx or a top-level component with useEffect.
...and render <AppWrapper /> in your index.tsx immediately, without awaiting init.
Additional considerations
Your ErrorBoundary component will only catch errors after React components mount.
The blank screen resulting from the async init failing early is expected if you do not render anything on error.
React.StrictMode double-mounts components in dev, but does not cause blank screens by itself.
Always provide a fallback UI in places where async setup can fail.
TL;DR
The blank white screen is likely because your csrfTokenManager.init() failed before React rendered.
Your ErrorBoundary won’t catch that, because React is not mounted.
Fix by rendering a fallback error UI inside your IIFE’s catch block.
Or move CSRF init inside React tree and show loading/errors as normal React UI.
If you want, I can provide a full working minimal example of both approaches!
// src/index.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import reportWebVitals from './reportWebVitals.ts';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/i18n';
import AppWrapper from './AppWrapper'; // Use wrapper instead of App directly
const container = document.getElementById('root');
if (!container) {
throw new Error("Root element with id 'root' not found.");
}
const root = createRoot(container);
root.render(
<React.StrictMode>
<I18nextProvider i18n={i18n}>
<AppWrapper />
</I18nextProvider>
</React.StrictMode>
);
reportWebVitals(console.log);
Advantages of this approach:
The app renders immediately, showing loading UI while fetching CSRF token.
Any initialization errors render a clear error message inside React UI.
Your app components (via csrfTokenManager) can safely assume token is ready once rendered.
You keep React error boundaries fully effective for downstream components.
Easier to add other async initializations later on.
If you want, you can further improve AppWrapper by:
Displaying a spinner or progress bar in the loading state.
Adding retry logic on initialization failure.
Type-safe error handling and styling consistent with your UI.
If you want me to generate those improvements or help with integrating this into your existing routes or state management, just ask!
You init CSRF tokens once on mount inside SiteContent (or wherever appropriate).
While loading, you show a simple message "Loading security tokens...".
If there’s an error, you both show an alert (using showAlert) and render an error message in UI.
When ready, you render the normal routes.
Alerts are rendered in a common location, so error alerts appear uniformly.
Cleanup alerts on unmount to avoid stale messages.
You can style the loading/error messages or alerts consistent with your app UI/UX guidelines.
Alternative: If you want to block entire app until tokens ready
If your other routes/components (e.g. Main) depend on CSRF tokens too, you will want to do similar logic there or lift the init to a higher component that wraps both Site and Main.
In summary
Yes, it's perfectly valid and common to defer async setup like CSRF init deeper in your component tree.
Just ensure you handle loading and error states in the UI so users know what’s going on.
Your alert system is a good place to unify and show errors.
Just keep your initialization idempotent and only call once per app session!
If you want, I can help you provide a fully integrated example including your alert provider and global app structure with this pattern.
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
/**
The backend sends the CSRF token in the JSON response as a plain string.
While the backend also sets a CSRF cookie (e.g., named 'csrfToken'), this cookie's value
is signed and serialized by the Yii framework to prevent tampering.
That means the cookie does NOT contain the raw token string but a protected value
including a signature and serialized data.
Because of that, attempting to read the CSRF token directly from the cookie on the frontend
and compare it with the token from backend JSON response will fail due to mismatched formats.
Therefore, it is best practice to trust the backend JSON token directly for sending in headers
and not attempt to read or validate the CSRF token from the cookie value.
This approach avoids dealing with Yii's cookie signing mechanics on the client side,
simplifies the CSRF token management,
and ensures synchronization without false mismatches.
*/
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
This is a signed and serialized value, not raw token!
*/
export function getSignedCsrfTokenFromCookie(): string | undefined
{
const cookieValue = Cookies.get(CSRF_COOKIE_NAME);
Your fetchCsrfToken() already throws errors if the backend response is missing required data or the cookie is missing.
Adding throw error; in init()'s catch ensures your React component can catch the error and show alerts or UI messages.
Why is cookie _csrf undefined?
The backend might be failing to set the cookie due to CORS, cookie options (HttpOnly, SameSite), environment differences, or the request missing withCredentials: true.
You can debug this by inspecting network requests and response headers in your browser DevTools.
Ensure your axios apiClient sets { withCredentials: true }.
Confirm that your backend sets the cookie with proper domain/path and that your frontend and backend domains allow the cookie to be accessible in JS.
Summary
Add throw error; in init() catch to propagate errors.
Your React code will then correctly catch and show error alerts/UI.
Verify withCredentials and cookie settings to fix missing cookie value.
If using eslint, you’ll get a warning about missing showAlert in deps. You can:
Ignore that line in this specific case,
Or ensure showAlert is stable and include it safely.
Why does this matter?
React's useEffect dependencies track all variables used inside useEffect that come from outside scope. If those are new functions/objects every render, they cause new effects fire every render ⇒ infinite loop.
The "maximum update depth" is because your useEffect depends on a function (showAlert) that causes it to rerun every render. Fix by removing it from the dependency array and making sure showAlert is stable.
If you want, I can also help you refactor your alert hooks/provider to guarantee function stability!
This runs the effect only once at mount, ignoring showAlert stability.
Step 2: Check that showAlert is stable
If you want to add showAlert as dependency, make sure the alert hook/provider memoizes it:
tsx
// Inside your AlertProvider (or wherever showAlert is created), use useCallback:
const showAlert = useCallback((type: string, message: string) => {
// your existing implementation
}, []);
Then you can safely add showAlert to dependency array:
tsx
useEffect(() => {
// ...
}, [showAlert]);
Step 3: Prevent multiple alert push on every render
Because you call showAlert inside useEffect and store alert IDs in a useRef, you should be clean in your cleanup effect to avoid stacking alerts on future unmounts and remounts.
Put some console.log inside your effect and render to see how many times they trigger.
Check the implementation of your useAlert hook: possibly it recreates functions on every render.
TL;DR
Prefer empty deps [] on your useEffect that initializes CSRF and shows alert.
Memoize showAlert function in alert provider, or ignore it in deps with comment.
Careful with updates that cause infinite loops by making useEffect retrigger on every render.
If you want, I can help review your alert hook/provider to add memoization and stable references, preventing these issues!
useCallback
Why?
Without memoization, the handleAlert function is re-created every render.
If your useEventListener depends on handleAlert, it may unsubscribe and re-subscribe listeners every render, potentially causing performance issues or bugs.
Using useCallback stabilizes the function reference.
showAlert('info', 'This message will stay on screen.', null);
*/
const showAlert = (
type: string,
message: string,
duration: number | null = 6000
): number =>
{
const id = Date.now();// Unique ID for the alert
const alertClass = alertTypeClass[type] || 'alert-info';
// Add the new alert to the alerts state
setAlerts(prevAlerts => [...prevAlerts, { id, type: alertClass, message }]);
// Check if the duration is not null; if it's a number, set a timeout to dismiss the alert
if (duration !== null)
{
setTimeout(() => {
dismissAlert(id);
}, duration);
}
return id;// Return the ID for future reference
};
/**
dismissAlert function: Removes an alert from the alert state.
@param {number} id - The unique ID of the alert to remove.
*/
const dismissAlert = (id: number) =>
{
// Filter out the alert with the specified ID from the alerts state
setAlerts(prevAlerts => prevAlerts.filter(alert => alert.id !== id));
};
);
};
×
Error: Encountered two children with the same key, 1748052589701. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
▶ 16 stack frames were collapsed.
(anonymous function)
src/components/Site.tsx:81:5
78 |
79 | <div style={{ zIndex: 1051 }}>
80 | {alerts.map(({ id, type, message }) => (