Replies: 2 comments
-
|
any update? |
Beta Was this translation helpful? Give feedback.
-
|
Hello! This is a common race condition issue between client-side cookie setting and server action execution. The problem occurs because Solution 1: Implement Cookie Verification and Retry Logic const baseFetch = async ({
endPoint,
method = 'GET',
options = {},
queryParams = {},
body,
url,
headers = {},
retryCount = 0
}) => {
try {
const appCookies = await cookies();
let publicToken = appCookies.get('token')?.value;
if (!publicToken && retryCount < 2) {
await new Promise(resolve => setTimeout(resolve, 100));
return baseFetch({
endPoint,
method,
options,
queryParams,
body,
url,
headers,
retryCount: retryCount + 1
});
}
const locale = appCookies.get('NEXT_LOCALE')?.value || defaultLocale;
console.log('this is token : ', publicToken);
} catch (err) {
return {
error: err?.message || 'Unexpected error occurred',
};
}
};Solution 2: Use Headers Instead of Cookies for Authentication const onCreatePublicToken = async () => {
setIsCreatingPublicToKen(true);
setIsCreatePublicTokenError(null);
const publicTokenRequest = await generatePublicToken();
if (publicTokenRequest?.data?.access_token) {
dispatch(setPublicToken(publicTokenRequest?.data?.access_token));
setCookie('token', publicTokenRequest?.data?.access_token, {
maxAge: ONE_MONTH_IN_SECONDS,
});
await makeAuthenticatedRequest(publicTokenRequest.data.access_token);
router.refresh();
}
};Solution 3: Ensure Proper Cookie Configuration setCookie('token', publicTokenRequest?.data?.access_token, {
maxAge: ONE_MONTH_IN_SECONDS,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
});Solution 4: Add Server-Side Token Validation const appCookies = await cookies();
let publicToken = appCookies.get('token')?.value;
if (!publicToken) {
console.warn('Token missing in server action, generating new one');
const newToken = await generateServerSideToken();
if (newToken) {
publicToken = newToken;
}
}The most reliable approach is Solution 1 with retry logic, as it accounts for the timing issue between client-side cookie setting and server action execution. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
setting cookie inside client component forward by router.refresh sometimes not avilable to server action
Additional information
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions