Persistence: Data persists across sessions and page reloads until explicitly cleared by the app or user.
API: Simple synchronous API (localStorage.setItem(), localStorage.getItem()).
Use Case: Storing small amounts of simple data (e.g., user preferences, UI state).
Performance: Blocking synchronous API can potentially slow down the main thread if used excessively.
Data Format: Strings only; for objects, you need to serialize with JSON.stringify() and deserialize with JSON.parse().
Security: Accessible by any script running on the same origin — no built-in encryption.
2. IndexedDB
Type: Asynchronous, transactional database system for client-side storage.
Storage Limit: Much larger storage capacity than Local Storage (often hundreds of MBs or more, depends on browser and user consent).
Persistence: Data persists indefinitely unless deleted.
API: Complex asynchronous API, usually accessed via promises or wrappers like idb.
Use Case: Storing large amounts of structured data (e.g., files, images, user-generated data, offline app data).
Performance: Non-blocking; can store complex objects, blobs, and more.
Data Format: Supports structured clones — can store objects, arrays, blobs, etc. — no need to manually serialize.
Security: Same-origin policy applies; no encryption by default.
3. Saving in Memory (React State / JS Variables)
Type: Volatile, in-memory storage.
Storage Limit: Limited by browser memory; typically fast access.
Persistence: Data lasts only while the app/page is open; lost on page reload or navigation.
API: React state hooks (useState, useReducer) or simple JS variables/refs.
Use Case: Temporary UI state, intermediate data processing, data that doesn't need persistence across reloads.
Performance: Very fast, immediate access.
Data Format: Any JS data type.
Security: Data exists only in the client memory context at runtime.
Quick Summary Table
Feature
Local Storage
IndexedDB
In-Memory (React state, vars)
Data Type
String only
Structured (objects, blobs)
Any JS type
Size Limit
~5-10 MB
Much larger (100+ MB)
Limited by memory
Persistence
Persistent (until cleared)
Persistent (until cleared)
Temporary (page session only)
API
Synchronous (blocking)
Asynchronous (non-blocking)
Native JS / React state hooks
Complexity
Simple
Complex
Simple
Use Case
Small, simple data
Large, complex, structured data
Temporary app state, UI state
Access Speed
Fast but blocks main thread
Fast and async, no blocking
Fastest, immediate
When to Use What?
Local Storage: Store small preferences, theme settings, or user tokens for persistent but simple data.
IndexedDB: Store large data sets, offline content, caches, or complex data structures requiring transactions.
In Memory (React state): Manage temporary UI state that doesn’t need persistence beyond the current session.
If you want I can also provide examples of how to use each method in React!
User
so saving a jwt token for react app, best practice for frontend
Assistant
Great question! Storing JWT tokens securely on the frontend is crucial to protect your app from common attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).
Best Practices for Storing JWT Tokens in a React App:
1. Avoid Local Storage for JWTs if Possible
LocalStorage is vulnerable to XSS attacks because any malicious script can read the token and send it to an attacker.
So, avoid storing JWTs directly in localStorage or sessionStorage if you want better security.
2. Use HTTP-only Secure Cookies (Recommended if Backend Supports It)
Store JWT tokens in an HTTP-only, Secure, SameSite cookie set by the server.
This means the cookie:
Is inaccessible via JavaScript (protects against XSS).
Is only sent over HTTPS (protects against MITM).
Can have the SameSite attribute set to Strict or Lax to reduce CSRF risks.
Flow:
After login, backend sets the JWT in an HTTP-only cookie.
Frontend sends requests with the cookie automatically.
Backend validates the token.
3. If Using Local Storage or Session Storage:
If you must store the JWT token in localStorage/sessionStorage, then:
Implement strong Content Security Policy (CSP) headers on your site to reduce XSS risk.
Sanitize all inputs and avoid any unsafe dangerouslySetInnerHTML React usage.
Consider token expiration and refresh tokens.
Do not store sensitive user data inside the token.
If the token contains sensitive scopes, consider short expiry times.
4. Keep Tokens in React Memory/state with Refresh Flow (Less Common)
Store the JWT in React state or a context—but this means the token disappears on page refresh!
Typically combined with refresh token in an HTTP-only cookie, the app fetches a new access token on app load.
This minimizes persistent storage and reduces exposure.
Summary Table for JWT Storage Options:
Storage Option
Pros
User
so its best to store in a cookie or indexedDB? what is the likelyhood of indexedDB not be accessable? or useable for a app
Assistant
Great follow-up! Let me clarify the trade-offs between HTTP-only cookies and IndexedDB as storage for JWTs, and address your questions about IndexedDB availability.
1. Is IndexedDB a Good Place to Store JWT Tokens?
IndexedDB is primarily designed for storing large amounts of structured data, including files, objects, blobs, and so forth.
It is accessible via JavaScript, so any script running on your page can read the contents stored there.
IndexedDB is not inherently more secure than localStorage or sessionStorage—it’s subject to the same XSS vulnerabilities if your app is compromised.
Because JWTs are sensitive tokens that can be abused if stolen, IndexedDB does not provide security benefits over localStorage.
IndexedDB is asynchronous and slightly more complex API-wise than localStorage, but that doesn't affect security for tokens.
In summary: IndexedDB is not a secure way to store JWT tokens because it's accessible via JavaScript just like localStorage and vulnerable to XSS.
2. Is IndexedDB Always Available? What’s the Likelihood It Might Not Be Available?
IndexedDB is supported by all major modern browsers (Chrome, Firefox, Edge, Safari).
On very old browsers, or some privacy-focused browsers/settings (e.g., Safari in Private Mode), IndexedDB can be disabled or limited.
For example, Safari (especially on iOS) can have buggy or limited IndexedDB support in certain private browsing modes.
Even when available, quota limits and storage clearing policies vary and can affect persistence.
Bottom line: IndexedDB is generally reliable and available for typical users, but there are edge cases (private/incognito modes, very restrictive privacy settings) where it can fail or be unavailable.
3. Is it Better to Store JWTs in Cookies or IndexedDB?
Aspect
HTTP-only Secure Cookies
IndexedDB
Security Against XSS
Good (JS cannot read HTTP-only cookies)
None (JS can read data)
Persistence
Persistent (unless cleared)
Persistent but can be cleared
CSRF Protection
User
so im using cors between the backend and frontend (yii2 to react), csrf token for forms, bearers with a user_key instead of int id for access. I just dont know where to save the jwt token(user_key) in the frontend and make it accessable for me(the app)
Assistant
Thanks for the context! Since you’re using:
CORS between your Yii2 backend and React frontend,
CSRF tokens for form submissions,
Bearer tokens with user_key for access,
the main challenge is storing the JWT token securely yet making it accessible to your React app so that you can attach it as a Bearer token in API requests.
What's typical and recommended in this architecture?
Option 1: Store JWT in Memory or React State + Refresh tokens in HTTP-Only Cookies
Store the JWT (access token) in React state or a JavaScript variable (in-memory).
On page refresh, the JWT will be lost, so use a refresh token stored in an HTTP-only cookie to get a new access token silently.
This avoids localStorage or IndexedDB entirely, reducing XSS risk.
All API requests add the JWT from memory in the Authorization header:
js
Authorization: Bearer <jwt-token>
Refresh token cookie is sent automatically with requests.
Pros:
JWT is never persisted in storage visible to JS.
Minimized XSS risk.
Cons:
User gets logged out on refresh if refresh flow isn’t implemented.
Requires backend endpoint for refreshing tokens.
Option 2: Store JWT in localStorage or sessionStorage
Store JWT token (your user_key) in localStorage or sessionStorage.
On app startup, read token from storage and set to React state.
Attach token in Authorization header for API calls.
Use short-lived JWTs and refresh tokens for better security.
Pros:
Easy to implement and access token from anywhere in your app.
Persisted across page reloads.
Cons:
Vulnerable to XSS attacks since JS can access localStorage/sessionStorage.
Needs good protection practices.
Option 3: Store JWT in HTTP-only SameSite cookie (recommended for security)
User
"Mitigate XSS by sanitizing inputs, CSP headers, avoiding unsafe JS execution."
Recommendations for all these throughout my the app, should a hook or util file used?
does react come with a way to handle cookies? and write to them? and read from them?
"React app cannot read this cookie directly (can't access token in JS).
API calls include cookie automatically (with credentials: 'include' in fetch/axios)."
How does this work?
Assistant
Great questions! I'll tackle your questions in two parts:
1. Mitigating XSS in React apps: Best practices and implementation approaches
XSS (Cross-Site Scripting) attacks commonly happen when unsafe user input ends up being rendered or executed in your app. React helps a lot by default but you still need disciplined practices.
Key XSS mitigations in React apps:
Avoid using dangerouslySetInnerHTML unless absolutely necessary. If you must use it, sanitize the HTML before rendering using libraries like DOMPurify.
Sanitize user inputs where they may reflect into your app (search boxes, comments, etc.)
Use libraries like DOMPurify or sanitize-html to clean any HTML string inputs.
Implement a Content Security Policy (CSP) header on your server
This instructs the browser to restrict what JS, CSS, images can load and run. For React apps, something basic might look like:
This severely limits the ability of attackers to inject malicious scripts or load dangerous resources.
Avoid unsafe JS code execution (e.g., no eval, new Function(), or dynamic script injections).
Use React's built-in escaping:
React automatically escapes strings inserted into JSX (e.g., <div>{userInput}</div>), so raw user input will not be interpreted as HTML by default.
Structure for sanitation in a React app:
Create utility functions for sanitization (e.g., a sanitizeInput function wrapping DOMPurify).
Use these utilities whenever you accept or display rich text or HTML from users.
If you use dangerouslySetInnerHTML, create a custom Hook or component that sanitizes the HTML before rendering.
Example utility file ():
User
"
A runnable example of a React fetch request with cookies and a Yii2 backend setting cookies.
Utility files or hooks to sanitize HTML safely.
CSP header examples for Yii2.
"
yes
Assistant
Certainly! Below you'll find examples for all three:
1. Runnable example: React fetch request with cookies & Yii2 backend setting cookies
Yii2 backend — setting HTTP-only cookie with JWT
In your controller action that handles login, after generating your JWT token:
php
public function actionLogin()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$request = \Yii::$app->request->post();
// Validate login here, generate JWT token
$jwt = YourJwtHelper::generateToken($request['username']);
// Set HTTP-only cookie with JWT token for frontend with cross-origin rules
$cookie = new \yii\web\Cookie([
'name' => 'token',
'value' => $jwt,
'httpOnly' => true,
'secure' => true, // Only for HTTPS in production!
'sameSite' => \yii\web\Cookie::SAME_SITE_NONE, // Needed for cross-site cookies
'path' => '/',
'expire' => time() + 3600, // optional expiration
]);
\Yii::$app->response->cookies->add($cookie);
return ['success' => true];
}
Important Yii2 CORS config snippet (in your config file), to allow credentialed cross-origin cookies:
React frontend — fetch with cookie (credentials included)
jsx
User
app backend web config:
code
// @url https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies
'session' => [
'class' => 'yii\web\Session',
'timeout' => 1440,// Session timeout in minutes; default is 1440 (24 hours)
//'name' => 'YOUR_SESSION_NAME',// Set a custom session name
'cookieParams' => [
'lifetime' => 0,// 0 means until the browser is closed
'path' => '/',
'domain' => '',// Domain for the cookie
'secure' => false,// Set to true if using HTTPS
'httponly' => true,
'samesite' => 'Lax',// Use 'Strict' or 'None' based on your needs
],
],
public function actionLogin()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
code
$request = \Yii::$app->request->post();
// Validate login here, generate JWT token
$jwt = YourJwtHelper::generateToken($request['username']);
// Set HTTP-only cookie with JWT token for frontend with cross-origin rules
$cookie = new \yii\web\Cookie([
'name' => 'token',
'value' => $jwt,
'httpOnly' => true,
'secure' => true, // Only for HTTPS in production!
'sameSite' => \yii\web\Cookie::SAME_SITE_NONE, // Needed for cross-site cookies
'path' => '/',
'expire' => time() + 3600, // optional expiration
]);
\Yii::$app->response->cookies->add($cookie);
return ['success' => true];
}
so with my config, still likely the best to set the jwt token whenever its needed aka signup, login and unset at logout?
Assistant
Yes, your understanding and approach are on the right track. Here's a detailed explanation in the context of your Yii2 backend config and JWT cookie management:
1. Storing JWT Token in HTTP-only Cookie on Login/Signup
Set the JWT token cookie when a user successfully logs in or signs up (i.e., whenever you issue or renew a JWT).
Yes, always explicitly clear that cookie when the user logs out.
You can do it in your logout action by setting the cookie with an expiration in the past:
php
public function actionLogout()
{
\Yii::$app->response->cookies->remove('token'); // Remove from response (to send removal header)
// OR explicitly overwrite cookie with past expiry:
\Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => 'token',
'value' => '',
'expire' => time() - 3600,
'httpOnly' => true,
'secure' => true,
'sameSite' => \yii\web\Cookie::SAME_SITE_NONE,
'path' => '/',
]));
return ['success' => true];
}
User
'session' => [
'class' => 'yii\web\Session',
'timeout' => 1440,// Session timeout in minutes; default is 1440 (24 hours)
//'name' => 'YOUR_SESSION_NAME',// Set a custom session name
'cookieParams' => [
'lifetime' => 0,// 0 means until the browser is closed
'path' => '/',
'domain' => '',// Domain for the cookie
'secure' => false,// Set to true if using HTTPS
'httponly' => true,// If true JavaScript can't access it, mitigating XSS risk
'samesite' => 'Lax',// Use 'Strict' or 'None' based on your needs
],
],
these settings are for development only, during production, sameSite will be strick, secure will be true, etc
Assistant
Exactly! Your understanding is spot on.
Here’s the best practice for your session configuration in different environments:
Development environment (e.g., localhost, HTTP)
secure => false (because you may not be running HTTPS locally)
sameSite => 'Lax' or 'Strict' (depending on whether you need cross-site requests during testing)
secure => true (requires HTTPS so cookie only sent over secure connections)
sameSite => 'Strict' (most secure, but can use 'Lax' if you need some cross-site usage; 'None' only if cross-site cookies are needed with Secure)
httponly => true
domain => your site domain (e.g., .example.com) if you want cookies to work on subdomains
Example:
php
'cookieParams' => [
'lifetime' => 0,
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict', // or 'Lax' depending on your needs
],
Why these changes?
secure: true: Essential in production to prevent cookies from being sent over unencrypted HTTP requests (which exposes them to sniffing).
sameSite: 'Strict': Prevents browser from sending cookies with cross-site requests, protecting against CSRF. You can relax it to 'Lax' if you have legitimate cross-site GET requests.
User
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true,// send cookies for CORS requests automatically
headers:
{
'Content-Type': 'application/json',
},
timeout: 10000,// Aborts the request and throws an error after 10 seconds
});
apiClient.interceptors.request.use((config) =>
{
const token = localStorage.getItem('jwtToken');//|| userJwtToken;// TODO - Or use context/state store
code
if (token)
{
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
these are within apiClientServices.ts
Assistant
Thanks for sharing your axios setup! I'll give you some tailored insights and recommendations based on this snippet and the context of JWT + cookies + React app.
Your current apiClient overview
ts
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true, // send cookies with CORS requests
headers: {
'Content-Type': 'application/json',
},
timeout: 10000,
});
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('jwtToken'); // loading token from localStorage
if (token) {
config.headers['Authorization'] = `Bearer ${token}`; // attach JWT token in header
}
return config;
});
Observations and Recommendations
1. Using both cookies and Authorization header for JWT is redundant
If you store the JWT token in an httpOnly cookie, the browser sends the cookie automatically when you use withCredentials: true.
In that case, you DON'T need to manually set the Authorization: Bearer <token> header in API requests because the backend uses the cookie to check authentication.
Trying to manually send an Authorization header with a token stored in localStorage defeats the purpose of httpOnly cookies (which JS cannot access).
It's important to choose one method for your token transport:
Cookie-based auth: Store JWT in httpOnly cookie, send cookie automatically (withCredentials: true), backend reads JWT from cookie, no manual Authorization header needed in frontend.
Bearer token auth: Store JWT in localStorage/sessionStorage or React state, attach explicitly in Authorization header on every request, do not use withCredentials: true or cookies (unless your API also needs cookies for sessions).
2. If you are storing JWT in localStorage
User
"1. Using both cookies and Authorization header for JWT is redundant
code
If you store the JWT token in an httpOnly cookie, the browser sends the cookie automatically when you use withCredentials: true.
In that case, you DON'T need to manually set the Authorization: Bearer <token> header in API requests because the backend uses the cookie to check authentication.
Trying to manually send an Authorization header with a token stored in localStorage defeats the purpose of httpOnly cookies (which JS cannot access). "
If this is redundant, write a comment for my code and I will comment out that section explaining why
Assistant
Certainly! Here's a comment you can add above the relevant section in your code, explaining why the manual Authorization header is redundant when using httpOnly cookies and should be commented out:
ts
apiClient.interceptors.request.use((config) =>
{
// NOTE: If you store the JWT in an HTTP-only secure cookie and use `withCredentials: true`,
// the browser automatically sends the cookie with every request.
// In this case, manually attaching the Authorization header with the JWT
// from localStorage is redundant and defeats the purpose of using HTTP-only cookies,
// since HTTP-only cookies are inaccessible to JavaScript.
// To maintain security best practices and avoid token duplication,
// comment out or remove the following token retrieval and header assignment.
/*
const token = localStorage.getItem('jwtToken');
if (token)
{
config.headers['Authorization'] = `Bearer ${token}`;
}
*/
return config;
});
This clearly explains why that code should be commented out if you're using httpOnly cookies for JWT storage.
User
"2. If you are storing JWT in localStorage
code
Then your current interceptor makes sense:
Reads token from localStorage.
Appends it to Authorization header.
withCredentials can remain false (default), unless you also need to send cookies for other purposes.
But storing in localStorage exposes you to XSS risks unless you have strong mitigation.
"
im storing in localStorage as a test, goal is to move the jwt token into a cookie to reduce the risk of a xss attack
Assistant
Got it! Here's a comment you can add to your interceptor or your codebase explaining that storing JWT in localStorage is a temporary/testing choice, with the plan to migrate to httpOnly cookies later for improved security:
ts
apiClient.interceptors.request.use((config) =>
{
// Currently reading JWT token from localStorage and attaching it as
// an Authorization header. This works for testing and development,
// but storing JWTs in localStorage exposes the app to XSS risks,
// since malicious scripts could access this storage.
//
// The goal is to transition to storing JWTs in HTTP-only secure cookies,
// which are inaccessible to JavaScript and mitigate XSS attacks.
//
// Once the backend and frontend support the cookie-based auth flow,
// this logic should be removed and replaced with relying on cookies sent automatically
// by the browser (with `withCredentials: true`).
const token = localStorage.getItem('jwtToken');
if (token)
{
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
This documents your current approach as a temporary measure and explains the security motivation behind migrating to cookies.
User
apiClient.interceptors.request.use((config) =>
{
code
return config;
});
do i need this then if im not using it? or do i need to return anything if the main part i was using it for is commented out now
Assistant
Good question!
If your interceptor no longer modifies the request config (because you commented out the token injection or any other logic), then the interceptor isn't doing anything useful anymore.
Do you need the interceptor if it just returns config unchanged?
Technically no, you can remove the interceptor entirely.
If you want to keep it as a placeholder for future logic, you can leave it, but it's redundant.
About returning the config
You must return the config object from the interceptor function so the request proceeds.
Returning nothing or failing to return will break the axios request flow.
apiClient.interceptors.request.use((config) => {
// TODO: Add request logic (e.g., attach token) here
return config; // Must always return config!
});
TL;DR
If interceptor does nothing, just remove it.
If kept for future, keep it returning config.
Always return config or a Promise resolving to it from request interceptors.
Let me know if you want me to help clean up your apiClient!
User
case 401:
// Unauthorized — handle auth refresh or redirect login
logger.error('apiClientServices.ts', 'Error 401 Unauthorized:', error);
code
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
// TODO: Add logic to refresh auth token here and retry the original request
// Or redirect the user to the login page if refresh is unavailable or fails
/* Example pseudo-code:
const refreshed = await tryRefreshToken();
if (refreshed)
{
// Update the failed request with new token and retry
error.config.headers['Authorization'] = `Bearer ${newToken}`;
return apiClient.request(error.config);
}
else
{
redirectToLogin();
}//*/
break;
so i need to create a service to call for a refresh token if need be:
export const ENDPOINTS =
{
security: {
csrfToken: 'api-security/csrf-token',// GET
jwtToken: 'api-security/jwt-token',// GET
},
// src/services/csrfServices.ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
return { csrfParam, csrfToken };
}
something like this?
Assistant
You're exactly on the right track! To handle token refresh on 401 errors, you want to:
Add a refresh token endpoint call in your retry logic.
Create a service (like your fetchCsrfToken) that calls the refresh token API endpoint.
Retry the failed request with the new token.
Redirect to login if refreshing fails.
Here’s a step-by-step example approach based on your setup:
1. Define a refresh token endpoint (add to your ENDPOINTS):
ts
export const ENDPOINTS = {
security: {
csrfToken: 'api-security/csrf-token', // GET
jwtToken: 'api-security/jwt-token', // GET (current JWT)
refreshToken: 'api-security/refresh-token', // POST for refresh
},
// other endpoints...
};
2. Create a refresh token service method (src/services/authServices.ts):
ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
export async function tryRefreshToken(): Promise<string | null> {
try {
// call refresh token endpoint. Assumes refresh token sent via httpOnly cookie.
const response = await apiClient.post(ENDPOINTS.security.refreshToken, {}, {
withCredentials: true, // important to send cookies
});
// Assume backend sends new JWT token in response body
const newToken = response.data?.jwtToken;
if (newToken) {
// Update your token storage, e.g. localStorage
localStorage.setItem('jwtToken', newToken);
return newToken;
}
return null;
} catch (err) {
console.error('Failed to refresh token:', err);
return null;
}
}
3. Update your axios response interceptor in to handle 401:
User
// src/services/authServices.ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
export async function tryRefreshToken(): Promise<string | null>
{
try
{
// call refresh token endpoint. Assumes refresh token sent via httpOnly cookie.
const response = await apiClient.post(ENDPOINTS.security.refreshToken, {},
{
withCredentials: true,// important to send cookies
});
code
// Assume backend sends new JWT token in response body
const newToken = response.data?.jwtToken;
if (newToken)
{
// Update your token storage, e.g. localStorage
localStorage.setItem('jwtToken', newToken);
return newToken;
}
return null;
}
catch (error)
{
console.error('Failed to refresh token:', err);
return null;
}
}
Why do you keep suggesting localStorage when we agreed thats a terrible idea
Assistant
Great point — thanks for flagging!
You're absolutely right: if your goal is to move away from storing JWTs in localStorage (because of XSS risks) and instead rely on httpOnly cookies, you should not store tokens in localStorage at all.
Why did I mention localStorage?
In many token refresh flow examples, the access token (JWT) is stored in localStorage or React state because httpOnly cookies cannot be read by JavaScript (so you can't dynamically put them in Authorization headers).
If you are using cookies exclusively for authentication (storing both access token and refresh token as httpOnly cookies and do all auth server-side), then you don’t need to store the JWT token anywhere in JavaScript.
In that cookie-only approach:
Backend reads JWT from cookie.
Frontend sends API requests with withCredentials: true but never attaches Authorization header manually.
Refresh token calls also happen transparently via cookie.
What should your refresh token function do if you don’t want to store tokens in localStorage?
Simply call the refresh endpoint with withCredentials: true so the refresh cookie is sent.
Backend issues a new JWT cookie (httpOnly cookie).
No JWT token is sent back in the response body (or if it is, you don’t store it in localStorage).
Frontend continues sending requests with cookie attached.
No need to update any token in JS memory or localStorage.
Updated version of your refresh function without storing the token in localStorage:
ts
export async function tryRefreshToken(): Promise<boolean> {
try {
// call refresh token endpoint; refresh token sent automatically via cookie
await apiClient.post(ENDPOINTS.security.refreshToken, {}, {
withCredentials: true,
});
// backend sets new JWT cookie, so just return success
return true;
} catch (error) {
console.error('Failed to refresh token:', error);
return false;
}
}
And update the 401 interceptor accordingly:
User
so why can i do the token within this:
code
case 401:
// Unauthorized — handle auth refresh or redirect login
logger.error('apiClientServices.ts', 'Error 401 Unauthorized:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
// TODO: Add logic to refresh auth token here and retry the original request
// Or redirect the user to the login page if refresh is unavailable or fails
/* Example pseudo-code:
const refreshed = await tryRefreshToken();
if (refreshed)
{
// Update the failed request with new token and retry
error.config.headers['Authorization'] = `Bearer ${newToken}`;
return apiClient.request(error.config);
}
else
{
redirectToLogin();
}//*/
break;
Because you (the JS code) have direct control over the token, and it’s part of the request headers.
2. When you store JWT tokens in httpOnly cookies:
Your frontend cannot access the token at all since httpOnly cookies are inaccessible to JavaScript.
The token (JWT) is sent automatically by the browser with every request if you use { withCredentials: true }.
When you call your refresh token API, backend issues a new JWT cookie (httpOnly) in the response headers.
There is no token in the JS response body to grab or add to header manually.
So your interceptor cannot (and should not) update Authorization header with a token.
Instead, just retry the request as-is, knowing the browser will send the updated cookie automatically.
Example interceptor logic for cookie-auth:
ts
User
so let me get this rgiht, you still think i should add:
const refreshed = await tryRefreshToken();
if (refreshed) {
// no need to modify originalRequest headers because cookie is sent automatically
return apiClient(originalRequest);
} else {
window.location.href = '/login';
}
to the:
apiClient.interceptors.request.use((config) =>
{
and leave the switch case:
code
case 401:
// Unauthorized — handle auth refresh or redirect login
logger.error('apiClientServices.ts', 'Error 401 Unauthorized:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
// TODO: Add logic to refresh auth token here and retry the original request
// Or redirect the user to the login page if refresh is unavailable or fails
/* Example pseudo-code:
const refreshed = await tryRefreshToken();
if (refreshed)
{
// Update the failed request with new token and retry
error.config.headers['Authorization'] = `Bearer ${newToken}`;
return apiClient.request(error.config);
}
else
{
redirectToLogin();
}//*/
break;
as just a logger?
Assistant
Thanks for clarifying! Let's get it all straight:
1) Where does the 401 refresh logic belong?
The 401 error handling, token refresh, and request retry logic belongs inside the axios response interceptor, not inside the request interceptor.
The request interceptor modifies outgoing requests before sending (e.g., attach tokens). The response interceptor handles errors coming back from the server.
2) Your existing switch (error.response.status) block inside response error handling
You likely have something like:
ts
apiClient.interceptors.response.use(
response => response,
(error) => {
switch(error.response?.status) {
case 401:
// Your logging and alert code here
break;
// other cases
}
return Promise.reject(error);
}
);
3) What to do with your current case 401 block?
You can strip out the commented-out refresh logic there and leave it just for logging and alerting.
The actual refresh + retry logic should be moved into the response interceptor function before (or instead of) the switch case.
4) Example fully working response interceptor for cookie-based refresh
ts
User
// src/services/apiClientServices.ts
import axios from 'axios';
import { API_BASE_URL } from '../constants/apiConstants';
import { emitEvent } from '../utils/eventBusUtils';
import logger from '../utils/loggerUtils';
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true,// send cookies for CORS requests automatically
headers:
{
'Content-Type': 'application/json',
},
timeout: 10000,// Aborts the request and throws an error after 10 seconds
});
apiClient.interceptors.request.use((config) =>
{
/**
* JWT in an HTTP-only Secure Cookie
* Storing the JWT in an HTTP-only secure cookie and use withCredentials: true,
* the browser automatically sends the cookie with every request.
*
* In this case, manually attaching the Authorization header with the JWT
* from localStorage is redundant and defeats the purpose of using HTTP-only cookies,
* since HTTP-only cookies are inaccessible to JavaScript.
*
* To maintain security best practices and avoid token duplication,
* comment out or remove the following token retrieval and header assignment.
*
const token = localStorage.getItem('jwtToken');
if (token)
{
config.headers['Authorization'] = Bearer ${token};
}//*/
code
return config;// Must always return config!
});
apiClient.interceptors.response.use
(
(response) => response,// Pass through successful responses unchanged
code
Assistant
Thanks for sharing your current full apiClientServices.ts. To integrate the 401 token refresh and retry flow properly while respecting your HTTP-only Secure Cookie auth approach, here’s how you can update it:
Updated apiClientServices.ts with proper 401 refresh handling for cookie-based tokens
ts
User
so having the 401 outside the switch prevents the infinite loop issue?
Assistant
Yes, exactly!
Why handling 401outside the switch (and checking a retry flag) helps prevent infinite loops:
When a request returns a 401 Unauthorized, you want to:
Attempt to refresh the token (e.g., get a new JWT cookie).
Retry the original request once with the new token.
If the retry also returns 401 (e.g., refresh failed or token invalid), do not keep retrying indefinitely — instead redirect to login or show error.
To implement this, you mark the request with a flag, usually _retry, indicating that this request has already been retried once:
js
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; // mark first retry
// try refresh token & retry request
}
If you instead put the 401 handling inside the switch statement without a retry check, every request retry returning 401 would trigger the refresh again, causing a continuous loop.
The switch case remains useful for handling other 401 scenarios, log alerts, or UI notifications after retry attempts have failed.
In short:
The _retry flag and first-line 401 handling outside the switch prevent infinite retry loops.
The switch then handles logging and alerts for all 401 errors regardless, including after a failed refresh and retry.
You can think of it as:
js
// Pseudo flow:
if (401 && not retried yet) {
mark retry = true
refresh token
retry request
} else {
// Already retried or other errors
// Just do logs, alerts in switch-case 401
}
If you want, I can explain this with example code or flow diagrams for clarity!
User
// src/services/apiClientServices.ts
import axios from 'axios';
import { API_BASE_URL } from '../constants/apiConstants';
import { emitEvent } from '../utils/eventBusUtils';
import logger from '../utils/loggerUtils';
import { tryRefreshToken } from './authServices'; // your refresh token utility
apiClient.interceptors.request.use((config) =>
{
/**
* JWT stored in HTTP-only Secure Cookies --> automatically sent via withCredentials
* So DO NOT manually set Authorization header from localStorage or JS.
/
/
const token = localStorage.getItem('jwtToken');
if (token) {
config.headers['Authorization'] = Bearer ${token};
}
*/
return config; // Always return config
});
apiClient.interceptors.response.use(
(response) => response, // Pass successful responses through unchanged
code
Assistant
Great question! Let me explain exactly where and how tryRefreshToken() is being used in your apiClientServices.ts:
Where is tryRefreshToken() called?
Look inside your axios response interceptor, specifically in this section:
A HTTP 401 Unauthorized status is received in the response — the token may have expired.
The interceptor checks if the request has been retried (using flag). If not retried yet:
User
// src/services/authServices.ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
export async function tryRefreshToken(): Promise<string | null>
{
try
{
const response = await apiClient.post(ENDPOINTS.security.refreshToken, {},
{
withCredentials: true,// important to send cookies
});
code
/**
* For Development only
* Storing the jwt token within the Local Storage
*
const newToken = response.data?.jwtToken;
if (newToken)
{
// Update your token storage, e.g. localStorage
localStorage.setItem('jwtToken', newToken);
return newToken;
}
return null;//*/
// backend sets new JWT cookie, so just return success
return true;
}
catch (error)
{
console.error('Failed to refresh token:', err);
return null;
}
}
If this is the frontend code, whats teh backend?
also I should never need to:
jwtToken: 'api-security/jwt-token',// GET (current jwt)
Only thing I need is use:
refreshJwtToken: 'api-security/refresh-jwt-token'
with:
export async function tryRefreshToken(): Promise<string | null>
{
try
{
const response = await apiClient.post(ENDPOINTS.security.refreshJwtToken, {},
{
withCredentials: true,// important to send cookies
});
code
/**
* For Development only
* Storing the jwt token within the Local Storage
*
const newToken = response.data?.jwtToken;
if (newToken)
{
// Update your token storage, e.g. localStorage
localStorage.setItem('jwtToken', newToken);
return newToken;
}
return null;//*/
// backend sets new JWT cookie, so just return success
return true;
}
catch (error)
{
logger.error('authServices.ts', 'Failed to refresh token:', error);
return null;
}
}
Assistant
You're completely right about the frontend code and the backend expectations. Let's break this down and I'll sketch what a backend setup might look like (specifically in Yii2 for your case) assuming your frontend just calls a refresh token endpoint that:
Accepts no JWT/access token in the request body or headers because token info is stored in httpOnly cookies.
Verifies the refresh token from the httpOnly cookie.
Issues a new access JWT cookie with the updated token.
Does not need to send JWT in response body (unless you want to, e.g., for development or special cases).
Returns success or failure status.
Frontend reminder: your code calls /refresh-jwt-token with withCredentials: true
1. Example controller action in Yii2 to refresh JWT token:
php
public function actionRefreshJwtToken()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// Check if refresh token cookie is present
$refreshToken = \Yii::$app->request->cookies->getValue('refresh_token');
if (!$refreshToken) {
\Yii::$app->response->statusCode = 401;
return ['success' => false, 'message' => 'No refresh token found'];
}
// Validate the refresh token (example using your own logic)
$userId = YourTokenService::validateRefreshToken($refreshToken);
if (!$userId) {
\Yii::$app->response->statusCode = 401;
return ['success' => false, 'message' => 'Invalid refresh token'];
}
// Generate new JWT access token for this user
$newJwt = YourTokenService::generateAccessToken($userId);
// Set new access token as httpOnly secure cookie
$accessTokenCookie = new \yii\web\Cookie([
'name' => 'access_token',
'value' => $newJwt,
'httpOnly' => true,
'secure' => true, // true in production with HTTPS
'sameSite' => \yii\web\Cookie::SAME_SITE_NONE, // cross site
'path' => '/',
'expire' => time() + 3600, // e.g., 1 hour expiry
]);
\Yii::$app->response->cookies->add($accessTokenCookie);
// Optionally refresh token cookie can also be rotated here
return ['success' => true]; // no JWT token in body, handled by cookie
}
User
Originally i was passinte the jwt token via the return:
user signup api controller:
code
$user = \Yii::$app->user->identity;
$jwtToken = JwtHelper::generateToken($user->user_key);
/**
* Frontend Expected Response Data
* @see frontend app/src/services/signupServices.ts
*/
return [
'success' => true,
'data' => [
'jwtToken' => $jwtToken,
'signupPhase' => $user->signup_phase,
// Alternatively send nextStep only when the flow is dynamic or branches required.
'nextPhase' => $user->getNextSignupPhase()
],
];
then we talked and you suggested cookies for security reasons and thats great! So im trying to rewrite all my code:
security api controller:
code
public function actionRefreshJwtToken(): array
{
$request = \Yii::$app->request;
if (!$request->isPost)
{
throw new BadRequestHttpException('Only POST requests are allowed.');
}
//\Yii::error("Request Post: " . json_encode($request->post()), __METHOD__);
/**
* User model $user
* Yii automatically calls User::findIdentityByAccessToken() validated with
* JWT token by HttpBearerAuth::class behavior
*/
$user = RoleHelper::userIdentity();
if (!$user)
{
throw new UnauthorizedHttpException('User not authenticated.');
}
// Check if refresh token cookie is present
$refreshToken = $request->cookies->getValue('refresh_token');
if (!$refreshToken)
{
\Yii::$app->response->statusCode = 401;
return [
'success' => false,
'message' => 'No refresh token found'
];
}
so i should check for the cookie first? and why refresh_token? when i was sending the jwtToken and grabbing it in the frontend I was
calling it jwtToken(backend) and userJwtToken useState(frontend). but you explained I did not need to save it how I was and can
store it directly into a cookie, I dont understand how to access it via the frontend cookie yet and not sure on how to rewrite these functions either
in the backend.
Assistant
Great questions — let me clarify the whole refresh token vs access (JWT) token flow, explain why you check for the refresh token cookie, and how this improves security compared to your previous setup.
You returned the JWT token in response body after signup/login.
Frontend saved it in localStorage or state (userJwtToken).
Frontend attached it manually to Authorization header.
This exposes JWT to XSS risk.
Suggested secure flow with cookies
Backend issues two tokens:
Access JWT in an HTTP-only secure cookie.
Refresh token in a separate HTTP-only secure cookie.
Frontend does NOT access (read) these cookies via JavaScript.
Frontend sends API requests with:
withCredentials: true in fetch/axios, so browser attaches cookies automatically.
Backend authenticates requests by validating JWT from cookie.
When backend responds 401 (expired JWT), frontend calls /refresh-jwt-token endpoint, again with withCredentials: true to send the refresh token cookie.
Backend validates refresh token cookie, issues new access token as new httpOnly cookie. Frontend retries original request.
React frontend just sends authenticated requests normally (with credentials: 'include' fetch option), no need to handle or read the token manually.
TL;DR
Best practice: Store JWT in secure, HTTP-only cookies set by your server, not in localStorage or sessionStorage. If you can't do that, take strong measures to mitigate XSS if storing tokens in localStorage/sessionStorage, and be mindful of token expiration and refresh.
If you want, I can also help with example React code for handling JWTs with secure cookies or localStorage. Just let me know!
Need SameSite attribute or CSRF tokens
Not applicable
Availability
Wide browser support
Wide browser support, but edge cases may exist in private modes
Complexity
Simpler (handled mostly by browser and backend)
More complex API, manual management
Token Accessibility in JS
Not accessible (more secure)
Accessible (less secure)
Conclusion:
When you want secure storage of JWT tokens with protection from XSS, HTTP-only cookies are the best choice.
IndexedDB does not provide additional security benefits for JWT storage and exposes you to XSS risks, similar to localStorage.
IndexedDB is great for offline storage of app data, but not recommended for sensitive tokens.
IndexedDB is mostly reliable, but you must handle fallback or degraded experience gracefully for rare cases where it is unavailable.
Bonus: How to Combine Approaches?
Some apps:
Store refresh tokens in HTTP-only cookies (more sensitive, long-lived).
Store short-lived access tokens in memory or sessionStorage for easier programmatic usage.
Rotate tokens frequently to reduce exposure.
If you want, I can help draft code snippets or architectural guidance based on your backend and frontend stack!
TL;DR: Use HTTP-only secure cookies to store JWT tokens for best security. IndexedDB is not recommended for JWT tokens despite good browser support because it is accessible via JS and thus vulnerable to XSS. IndexedDB's availability is high but not guaranteed in all privacy modes or browsers.
Store JWT as HTTP-only Secure cookie with SameSite=Lax or Strict set by backend.
React app cannot read this cookie directly (can't access token in JS).
API calls include cookie automatically (with credentials: 'include' in fetch/axios).
Backend reads JWT from cookie instead of Authorization header.
CSRF tokens are still important here for unsafe methods (POST/PUT/DELETE).
Pros:
Strong protection vs XSS (token inaccessible to JS).
Browser manages cookie so easy to send with request.
Cons:
More backend coordination required.
Can't manually inspect token in frontend JS.
Must handle CSRF carefully.
CORS requests need credentials: 'include' and correct CORS headers.
Given Your Setup:
Since you’re using CORS (requests come from a different origin), sending cookies cross-origin requires:
Backend sets cookies with Access-Control-Allow-Credentials: true.
Frontend fetch/axios uses credentials: 'include'.
Cookies must have SameSite=None and Secure flags on modern browsers for cross-site contexts.
You have CSRF tokens separately for form submissions, which is good.
So: Where to store the JWT (user_key) on the frontend?
Scenario
Recommendation
App can use HTTP-only SameSite cookies with CORS credentials mechanism
Store JWT in HTTP-only cookie; frontend does not access JWT in JS; backend reads it from cookie. Use credentials: 'include' in fetch.
You want frontend to read and use JWT actively (e.g. attach Bearer token in headers)
Store JWT in memory (React state) + refresh flow, or as fallback store in localStorage cautiously with strong security practices.
You want simpler setup and are OK with some security tradeoff
Store JWT token in localStorage. Implement CSP, input sanitization, and short token TTLs.
Recommended approach for best security and usability in your case:
Use HTTP-only cookies for storing tokens if you can update backend:
Backend issues cookie on login (Set-Cookie, HttpOnly, Secure, SameSite=None).
React app makes API calls with credentials: include.
Backend reads JWT from cookie.
You don’t handle the token in JS at all.
Use CSRF tokens on unsafe methods.
If backend cannot do cookies or you need JWT in React for Bearer header, then:
Store JWT token temporarily in React state/memory.
Persist token in sessionStorage as fallback if you want page reload persistence (accepting XSS risk).
Refresh token flow recommended to minimize exposure.
Example with localStorage + React:
jsx
// Save token after login
localStorage.setItem('jwt', token);
// Retrieve token on app load
const savedToken = localStorage.getItem('jwt');
const [jwt, setJwt] = React.useState(savedToken);
// Attach token in API request
fetch('https://api.example.com/protected', {
headers: {
'Authorization': `Bearer ${jwt}`,
}
});
Example for fetch with credentials to use cookie:
js
fetch('https://api.example.com/protected', {
method: 'GET',
credentials: 'include', // important to send cookies in cross-origin requests
})
Summary
If security is your priority and backend supports cookies + CORS credentials → store token in HTTP-only cookie and don't access token in React.
If you need to interact with token in React → store JWT in memory or localStorage, but protect your app from XSS accordingly.
Combine with refresh tokens & short-lived JWT access tokens.
Let me know if you want help implementing any particular flow or sample code!
utils/sanitize.js
js
import DOMPurify from 'dompurify';
export function sanitizeHtml(dirtyHtml) {
return DOMPurify.sanitize(dirtyHtml);
}
Example custom component:
jsx
import React from 'react';
import { sanitizeHtml } from '../utils/sanitize';
const SafeHtml = ({ html }) => (
<div dangerouslySetInnerHTML={{ __html: sanitizeHtml(html) }} />
);
You can then use <SafeHtml html={someUserContent} /> safely.
2. React and Cookies: How to read/write cookies and how HTTP-only cookies work
Does React have built-in cookie management?
No. React does NOT provide native APIs for reading/writing cookies. React is UI-focused and doesn’t include cookie utilities.
You use JavaScript’s standard document.cookie or third-party libraries like js-cookie to read/write cookies in normal (non-HTTP-only) cookies.
Example using js-cookie:
js
import Cookies from 'js-cookie';
// Set
Cookies.set('token', '123456', { expires: 7, secure: true });
// Get
const token = Cookies.get('token');
However, you cannot read or write HTTP-only cookies from JavaScript at all. This is a browser security feature.
How do HTTP-only cookies work?
HTTP-only cookies cannot be accessed by JavaScript (this protects tokens from XSS stealing).
Setting HTTP-only cookies must be done from the server, e.g., with Yii2 backend:
php
Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => 'token',
'value' => $jwt,
'httpOnly' => true,
'secure' => true, // sent only over HTTPS
'sameSite' => 'Lax', // or 'Strict' / 'None' depending on need
]));
When your React frontend makes API calls to the backend domain that set the cookie, the browser automatically sends those cookies with each request — no manual need to access or add token in headers.
Important for cross-origin CORS requests:
Because your React app is on a different origin than the Yii2 backend (CORS setup), some special handling is needed:
SameSite=None and Secure are required for cross-site cookies to be sent by modern browsers (over HTTPS).
credentials: "include" tells browser to send cookies for cross-origin requests.
The backend reads the JWT cookie and authenticates the user from it.
What does the React app see?
React cannot read the HTTP-only cookie (for security).
React doesn't need to manage the token manually in this case.
React just sends requests with credentials: 'include'.
Backend handles token authentication based on the cookie sent with the request.
Summary of the cookie process for JWT auth:
Step
Description
1. User logs in
Backend returns Set-Cookie header with JWT token (HttpOnly, Secure)
2. Cookie stored by browser
Cookie stored but inaccessible to JavaScript
3. React API request
React makes fetch request with credentials: 'include'
4. Browser attaches cookie
Browser automatically sends the cookie with request
5. Backend validates JWT cookie
Backend authenticates user from JWT in the cookie
6. React app receives response
React handles response without touching JWT directly
Wrapping Up
React doesn’t provide cookie management natively; you use JS APIs or libraries for normal cookies.
HTTP-only cookies are inaccessible to JS, which increases security.
In cross-origin setups, use credentials: "include" for fetch/axios and make sure your backend CORS and cookie settings allow it.
To mitigate XSS across the app: sanitize inputs, carefully use dangerouslySetInnerHTML, implement CSP headers, and follow React escape conventions.
If you want, I can help you with:
A runnable example of a React fetch request with cookies and a Yii2 backend setting cookies.
Utility files or hooks to sanitize HTML safely.
CSP header examples for Yii2.
Just let me know!
// Example login function to authenticate and get cookie set by backend
async function login(username, password) {
const res = await fetch('https://your-api-domain.com/login', {
method: 'POST',
credentials: 'include', // Important: allow sending/receiving cookies cross-origin
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (data.success) {
console.log('Login successful and cookie set!');
} else {
console.error('Login failed');
}
}
// Example of making an authenticated request to backend — cookie automatically sent
async function fetchProtectedData() {
const res = await fetch('https://your-api-domain.com/protected-api', {
method: 'GET',
credentials: 'include', // Important: send cookies with this request
});
if (res.ok) {
const data = await res.json();
console.log('Protected data:', data);
} else {
console.error('Failed to fetch protected data');
}
}
2. Utility file & hook for HTML sanitization with DOMPurify
Install DOMPurify:
bash
npm install dompurify
Utility file: src/utils/sanitize.js
js
import DOMPurify from 'dompurify';
// Sanitize a string containing HTML, e.g. user-generated content before displaying in React
export function sanitizeHtml(dirtyHtml) {
return DOMPurify.sanitize(dirtyHtml);
}
Hook to use sanitized HTML safely (src/hooks/useSanitizedHtml.js)
js
import { useMemo } from 'react';
import { sanitizeHtml } from '../utils/sanitize';
// Custom hook - returns sanitized HTML string (memoized)
export function useSanitizedHtml(html) {
return useMemo(() => sanitizeHtml(html), [html]);
}
'secure' => false means the cookie is sent over HTTP and HTTPS. For production / HTTPS environments, set 'secure' => true to ensure cookie is sent only over HTTPS.
'samesite' => 'Lax' is a reasonable default for same-origin requests, but for your cross-origin JWT cookie, you are overriding it by setting SameSite=None on the JWT cookie itself (good).
Session cookies and JWT cookies are separate; your JWT cookie config in actionLogin is independent of session config.
4. Summary Recommendations
When
What to do
Notes
On user login/sign up
Set JWT in httpOnly, Secure, SameSite=None cookie
Your current actionLogin setup is correct
On user logout
Remove/expire JWT cookie
Ensures user is fully logged out
On API/backend authenticated requests
Read JWT from cookie
Backend can verify user
Session config
Set secure and samesite properly
secure should be true in prod
Frontend API requests
Use credentials: 'include' to send cookies
Cookie sent automatically
Notes on Token Refresh and Expiry
With JWT expiration (expire), after the token expires, the browser will keep sending the old cookie unless you clear/update it.
You may want to implement:
A refresh token mechanism with longer life, also in httpOnly cookie.
An endpoint to refresh the JWT token before expiry, setting a new cookie.
This avoids forcing users to re-login frequently.
TL;DR
It is best practice to set the JWT token in this httpOnly, secure cookie whenever you generate it (login/signup/refresh), and remove it explicitly on logout. Your current approach aligns well with this.
If you want I can also help with sample code to do the cookie removal on logout and/or implement a refresh token flow!
httponly: true: Helps prevent XSS attacks by disallowing JavaScript access to the session cookie.
How to manage different configs?
Use Yii2 environment config files (e.g., web.php, web-prod.php) to override these parameters per environment.
Bonus: handling token refresh and automatic retries on 401
If you want full auth flow, intercept 401 errors, refresh token via cookie, then retry:
ts
apiClient.interceptors.response.use(
response => response,
async error => {
if (error.response.status === 401) {
// Refresh token flow: call backend refresh endpoint with credentials: include
try {
await axios.post('/refresh-token', {}, { withCredentials: true });
// Retry original request after refreshing token
return apiClient(error.config);
} catch (refreshError) {
// Redirect to login or logout user
}
}
return Promise.reject(error);
}
);
TL;DR
Storage / Auth method
axios config
Authorization header needed?
Notes
httpOnly secure cookies
withCredentials: true
NO
Recommended for security
localStorage/sessionStorage JWT
withCredentials: false / optional
YES
Easier but vulnerable to XSS
Mix of both
Depends, manage carefully
YES
More complex, needs refresh flow
If you want, I can help you refactor your apiClientServices.ts for the best fit based on your auth storage strategy. Just let me know!
apiClientServices.ts
ts
import { tryRefreshToken } from './authServices';
apiClient.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true; // Prevent infinite retry loop
const newToken = await tryRefreshToken();
if (newToken) {
// Attach new token to Authorization header
originalRequest.headers['Authorization'] = `Bearer ${newToken}`;
return apiClient(originalRequest); // Retry original request
} else {
// Refresh failed, redirect to login
window.location.href = '/login'; // adjust as needed
}
}
return Promise.reject(error);
}
);
4. Notes:
The refresh token is usually stored in an httpOnly cookie (so JS does not need to access it).
Your refresh endpoint reads the refresh token from cookie, issues a new access token.
The access token can be returned in the response payload (or set again as cookie).
You update your frontend-accessible token (localStorage or memory).
Retry the failed request after you get the new token.
5. Summary:
Your tryRefreshToken service calls the API to refresh JWT.
On 401, interceptor calls tryRefreshToken, updates the token, retries.
If refresh fails, redirect user to login page.
Make sure your backend supports the refresh token flow and CORS with credentials.
If you want, I can help you with a full working example of the refresh token flow!
ts
apiClient.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshed = await tryRefreshToken();
if (refreshed) {
// Retry original request; JWT cookie will be sent automatically by browser
return apiClient(originalRequest);
} else {
// Redirect to login if refresh failed
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);
Summary of secure cookie-based JWT flow:
Step
Description
JWT and Refresh tokens stored as httpOnly cookies
JS cannot access tokens, lowering XSS risk
Frontend sends requests with withCredentials: true
Browser attaches JWT cookie automatically
On 401 Unauthorized, frontend calls refresh endpoint with withCredentials: true
Backend sends new JWT cookie if refresh successful
Frontend retries original request, cookie is sent automatically
No need to store tokens in localStorage or React state
TL;DR
If using httpOnly cookies for JWT storage, do not store JWT in localStorage.
Tokens stay hidden from JS; backend handles authentication via the cookie.
Refresh endpoint triggers backend to set a new JWT cookie, no frontend token storage needed.
Update your refresh logic to reflect that — no storing tokens in JS.
If you want, I can help you convert your entire frontend auth flow to be cookie-only style based on this approach!
const refreshed = await tryRefreshToken();
if (refreshed) {
// no need to modify originalRequest headers because cookie is sent automatically
return apiClient(originalRequest);
} else {
window.location.href = '/login';
}
Summary Table:
Storage & Flow
Can JS read token?
Need to add Authorization header manually?
Interceptor retry approach
JWT in localStorage
Yes
Yes
Attach new token in header when retrying
JWT in httpOnly cookie
No
No
Retry request as-is; browser sends cookie
Why the difference matters in your case:
Your initial example interceptor with setting Authorization header on retry is correct for localStorage-based setup.
Your later approach without updating headers works for cookie-based setup.
Final thought:
If you want to move to cookie-based JWT auth (recommended for security), the interceptor should NOT set Authorization header — let browser handle cookies transparently.
If you continue to store your token in localStorage (less secure), your interceptor MUST set the header manually after refresh.
If you want, I can help you write your interceptor suitable for cookie-based auth or localStorage-based auth based on your current choice!
import { tryRefreshToken } from './authServices';
apiClient.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
// Try to refresh token via cookie-based refresh endpoint
const refreshed = await tryRefreshToken();
if (refreshed) {
// Retry original request — cookie(s) sent automatically by browser
return apiClient(originalRequest);
} else {
// Refresh failed — log and redirect user to login (or logout page)
logger.error('apiClientServices.ts', 'Token refresh failed, redirecting to login');
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
window.location.href = '/login'; // your login URL here
}
}
// For other errors or after failed retries
if(error.response?.status === 401) {
logger.error('apiClientServices.ts', 'Error 401 Unauthorized:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
}
return Promise.reject(error);
}
);
Keep minimal — just logging & alerting — refresh logic handled earlier in same function.
Request interceptor?
No — only for modifying outgoing requests, not response errors.
Should you retry after refresh?
Yes — retry original request after success refresh.
Should you manually update headers for cookie-based?
No — browser manages cookies, so no manual Authorization header needed.
So, your updated code structure should:
Remove the commented-out refresh/token update/retry from your switch-case 401.
Move refresh + retry logic into the async interceptor.
Use the switch-case 401 inside response error handler just for logging and UI alerting.
If you want, I can write the full cleaned-up interceptor based on your current setup — just ask!
async (error) =>
{
// Handle Axios timeout errors explicitly
if (error.code === 'ECONNABORTED' && error.message.includes('timeout'))
{
logger.warn('apiClientServices.ts', 'Request timed out:', error);
emitEvent('alert', { type: 'warning', key: 'alert.timeout' });
return Promise.reject(new Error('Request timed out. Please try again.'));
}
// Otherwise handle by HTTP status code
const status = error.response?.status;
switch (status)
{
case 400:
// Bad Request — maybe validation failed
logger.warn('apiClientServices.ts', '400 Bad Request:', error);
emitEvent('alert', { type: 'warning', key: 'alert.badRequest' });
break;
case 401:
// Unauthorized — handle auth refresh or redirect login
logger.error('apiClientServices.ts', 'Error 401 Unauthorized:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
// TODO: Add logic to refresh auth token here and retry the original request
// Or redirect the user to the login page if refresh is unavailable or fails
/* Example pseudo-code:
const refreshed = await tryRefreshToken();
if (refreshed)
{
// Update the failed request with new token and retry
error.config.headers['Authorization'] = `Bearer ${newToken}`;
return apiClient.request(error.config);
}
else
{
redirectToLogin();
}//*/
break;
case 403:
// Forbidden — user lacks permissions
logger.warn('apiClientServices.ts', '403 Forbidden:', error);
emitEvent('alert', { type: 'danger', key: 'alert.forbidden' });
// Maybe redirect or show permission error dialog
break;
case 404:
// Not Found — resource missing
logger.info('apiClientServices.ts', '404 Not Found:', error);
emitEvent('alert', { type: 'info', key: 'alert.notFound' });
break;
case 500:
// Server error — inform user, retry options, etc
logger.error('apiClientServices.ts', '500 Server Error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.serverError' });
break;
default:
// Other errors: network issues, etc.
logger.error('apiClientServices.ts', 'Unhandled error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unknownError' });
}
// handle 401, token refresh, global error logging here
return Promise.reject(error);
}
);
export default apiClient;
// src/services/apiClientServices.ts
import axios from 'axios';
import { API_BASE_URL } from '../constants/apiConstants';
import { emitEvent } from '../utils/eventBusUtils';
import logger from '../utils/loggerUtils';
import { tryRefreshToken } from './authServices'; // your refresh token utility
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true, // send cookies cross-origin automatically
headers: {
'Content-Type': 'application/json',
},
timeout: 10000,
});
apiClient.interceptors.request.use((config) =>
{
/**
* JWT stored in HTTP-only Secure Cookies --> automatically sent via `withCredentials`
* So DO NOT manually set Authorization header from localStorage or JS.
*/
/*
const token = localStorage.getItem('jwtToken');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
*/
return config; // Always return config
});
apiClient.interceptors.response.use(
(response) => response, // Pass successful responses through unchanged
async (error) => {
// Handle Axios timeout errors explicitly
if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
logger.warn('apiClientServices.ts', 'Request timed out:', error);
emitEvent('alert', { type: 'warning', key: 'alert.timeout' });
return Promise.reject(new Error('Request timed out. Please try again.'));
}
const status = error.response?.status;
const originalRequest = error.config;
if (status === 401 && !originalRequest?._retry) {
originalRequest._retry = true; // Prevent infinite loop
logger.warn('apiClientServices.ts', '401 Unauthorized - attempting token refresh');
try {
const refreshed = await tryRefreshToken();
if (refreshed) {
logger.info('apiClientServices.ts', 'Token refreshed - retrying original request');
// On refresh success, retry original request (cookies sent automatically)
return apiClient(originalRequest);
} else {
// Refresh failed => redirect to login
logger.error('apiClientServices.ts', 'Token refresh failed - redirecting to login');
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
window.location.href = '/login'; // adjust as needed
return Promise.reject(error);
}
} catch (refreshError) {
logger.error('apiClientServices.ts', 'Error during token refresh:', refreshError);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
window.location.href = '/login';
return Promise.reject(error);
}
}
// Other status code specific handling for logging and alerts
switch (status) {
case 400:
logger.warn('apiClientServices.ts', '400 Bad Request:', error);
emitEvent('alert', { type: 'warning', key: 'alert.badRequest' });
break;
case 403:
logger.warn('apiClientServices.ts', '403 Forbidden:', error);
emitEvent('alert', { type: 'danger', key: 'alert.forbidden' });
break;
case 404:
logger.info('apiClientServices.ts', '404 Not Found:', error);
emitEvent('alert', { type: 'info', key: 'alert.notFound' });
break;
case 500:
logger.error('apiClientServices.ts', '500 Server Error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.serverError' });
break;
default:
// Handles all other errors, e.g., network down, CORS, etc.
logger.error('apiClientServices.ts', 'Unhandled error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unknownError' });
}
return Promise.reject(error);
}
);
export default apiClient;
Explanation:
In the response interceptor, when getting a 401 Unauthorized error:
We check _retry flag on the request to prevent infinite retry loops.
Call your existing tryRefreshToken() function which calls the backend refresh endpoint. Backend sets a new JWT cookie.
If refresh succeeds, retry the original request. Since your JWT token is an httpOnly cookie, axios will send the new cookie automatically.
If refresh fails or errors, redirect user to login.
The commented-out code in the request interceptor remains commented, because for httpOnly cookie auth you do NOT manually set Authorization header.
Other HTTP status cases are handled with logging and user notifications as before.
What you should ensure on the backend:
The refresh endpoint (ENDPOINTS.security.refreshToken) reads the refresh token cookie and issues a new JWT cookie (httpOnly, Secure, SameSite).
CORS headers allow credentials and your frontend uses withCredentials: true.
Cookies are configured correctly (HttpOnly, Secure, SameSite=None if cross-site).
In summary
This setup supports secure cookie-based JWT flows.
You never expose JWT tokens to window/localStorage.
The frontend transparently retries failed requests after refreshing tokens.
Users get smoothly logged out on token expiration or refresh failure.
If you want help with:
The tryRefreshToken implementation,
Backend cookie settings,
Frontend logout or redirect flows
let me know!
async (error) => {
// Handle Axios timeout errors explicitly
if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
logger.warn('apiClientServices.ts', 'Request timed out:', error);
emitEvent('alert', { type: 'warning', key: 'alert.timeout' });
return Promise.reject(new Error('Request timed out. Please try again.'));
}
const status = error.response?.status;
const originalRequest = error.config;
if (status === 401 && !originalRequest?._retry) {
originalRequest._retry = true; // Prevent infinite loop
logger.warn('apiClientServices.ts', '401 Unauthorized - attempting token refresh');
try {
const refreshed = await tryRefreshToken();
if (refreshed) {
logger.info('apiClientServices.ts', 'Token refreshed - retrying original request');
// On refresh success, retry original request (cookies sent automatically)
return apiClient(originalRequest);
} else {
// Refresh failed => redirect to login
logger.error('apiClientServices.ts', 'Token refresh failed - redirecting to login');
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
window.location.href = '/login'; // adjust as needed
return Promise.reject(error);
}
} catch (refreshError) {
logger.error('apiClientServices.ts', 'Error during token refresh:', refreshError);
emitEvent('alert', { type: 'danger', key: 'alert.unauthorized' });
window.location.href = '/login';
return Promise.reject(error);
}
}
// Other status code specific handling for logging and alerts
switch (status) {
case 400:
logger.warn('apiClientServices.ts', '400 Bad Request:', error);
emitEvent('alert', { type: 'warning', key: 'alert.badRequest' });
break;
case 403:
logger.warn('apiClientServices.ts', '403 Forbidden:', error);
emitEvent('alert', { type: 'danger', key: 'alert.forbidden' });
break;
case 404:
logger.info('apiClientServices.ts', '404 Not Found:', error);
emitEvent('alert', { type: 'info', key: 'alert.notFound' });
break;
case 500:
logger.error('apiClientServices.ts', '500 Server Error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.serverError' });
break;
default:
// Handles all other errors, e.g., network down, CORS, etc.
logger.error('apiClientServices.ts', 'Unhandled error:', error);
emitEvent('alert', { type: 'danger', key: 'alert.unknownError' });
}
return Promise.reject(error);
}
);
export default apiClient;
so where is the tryRefreshToken being used?
_retry
_retry is set to true to prevent retry loops.
Your tryRefreshToken()function is called asynchronously.
This function should call your refresh API endpoint and return a boolean indicating success/failure.
If tryRefreshToken() returns true (refresh success):
The interceptor retries the original failed request (apiClient(originalRequest)).
Since you use httpOnly cookies, the browser sends the refreshed JWT cookie automatically.
If refresh fails (returns false or throws):
User is redirected to login page.
An alert is emitted.
In summary
tryRefreshToken() is called only when the response interceptor receives a 401 error and retry has not been done yet.
It enables automatic token refresh and request retry without requiring the user to re-login immediately.
If you want, I can also help you review or implement a robust tryRefreshToken() function based on your backend API!
2. Notes
You do not return the JWT to the frontend in the response body, it is sent as an httpOnly cookie.
The frontend never reads the JWT but the browser sends it automatically with subsequent API calls.
Refresh token should also be stored on the client as an httpOnly cookie.
You can rotate the refresh token cookie here to enhance security.
Make sure OPTIONS requests and CORS headers allow credentials and your domain.
3. Your endpoints constant could be:
ts
export const ENDPOINTS = {
security: {
refreshJwtToken: 'api-security/refresh-jwt-token', // POST only refreshes token via cookie
},
// other endpoints...
};
Summary:
Frontend calls ONLY the refresh endpoint (no current token needed in header or body).
Backend obtains refresh token from httpOnly cookie, verifies, and issues new JWT cookie.
This approach eliminates the need to expose tokens via localStorage, maximizing security.
Your tryRefreshToken() returns true or false based on backend success.
If you want, I can help you with a full example for Yii2 (including token generation and validation) and/or any additional flow, such as logout and CSRF protection.
Frontend never reads or stores tokens in JS storage — better security!
Why check for refresh_token cookie in your backend?
When your frontend calls /refresh-jwt-token, the backend does NOT receive the JWT (access token) because it is expired/invalid.
Instead, backend checks the refresh token cookie, which is:
Longer-lived token (valid maybe days or weeks).
Sent securely with the request (httpOnly, Secure cookies).
Used ONLY to issue a new access JWT cookie.
Without the refresh token cookie:
Backend must reject the refresh request (401 no refresh token found).
User must be logged out or asked to log in again.
How to rewrite your backend refresh function?
php
public function actionRefreshJwtToken(): array
{
$request = \Yii::$app->request;
if (!$request->isPost) {
throw new BadRequestHttpException('Only POST requests are allowed.');
}
// You don't authenticate user here by JWT, because it expired.
// You authenticate by verifying the refresh token from cookie:
$refreshToken = $request->cookies->getValue('refresh_token');
if (!$refreshToken) {
\Yii::$app->response->statusCode = 401;
return ['success' => false, 'message' => 'No refresh token found'];
}
// Validate the refresh token value - e.g. decode, check expiration, etc.
$userId = YourRefreshTokenService::validateRefreshToken($refreshToken);
if (!$userId) {
\Yii::$app->response->statusCode = 401;
return ['success' => false, 'message' => 'Invalid refresh token'];
}
// Generate new JWT access token
$newAccessToken = JwtHelper::generateToken($userId);
// Send new access token as httpOnly cookie:
$cookie = new \yii\web\Cookie([
'name' => 'access_token',
'value' => $newAccessToken,
'httpOnly' => true,
'secure' => true, // true in production
'sameSite' => \yii\web\Cookie::SAME_SITE_NONE, // cross-site if needed
'path' => '/',
'expire' => time() + 3600, // 1 hour
]);
\Yii::$app->response->cookies->add($cookie);
// Optionally rotate refresh token too
return ['success' => true];
}
Frontend usage
When calling /refresh-jwt-token, frontend does NOT send any token manually.
Uses withCredentials: true, browser sends cookies (including the refresh token cookie).
Backend validates refresh token cookie, issues new access token cookie.