In my opinion, the CSRF token should be stored in the main memory of your React application—as a variable held in react state
, preferably within a global react context
. Keep in mind that the CSRF token will be lost on a page refresh or when opening a new tab. To handle this, create an API endpoint (for example, GET /api/csrf-token
) on your server that generates and returns a token using contextual data (like the user's email, session, or user ID).
This endpoint should be called during the initial setup of your React app. While you might consider using the useEffect
hook, this can lead to race conditions. Instead, using useLayoutEffect
is advisable because it executes synchronously before the browser paints, ensuring that your authentication flow remains seamless.
For additional context, check out this article which outlines a similar approach.