I am attempting to modify the cookies stored in my browser from server side code (Next JS 14). This is relating to user authentication.
One of my cookies is called ssotoken is holds a JWT token. The other cookie holds a refresh token. In order to keep the ssotoken fresh, I have the following setup:
- All of my API calls (call to an external API service I have set up) are executed using react query in custom hooks on the client side.
- Prior to EVERY fetch request in these hooks, I call a client side utility function called getToken. The function gets the token, then calls a server side utility function called isTokenExpired:
export const getToken = async () => {
console.log("in get token");
const cookieVal = getCookie("impersonateToken") ?? getCookie("ssotoken");
const cookie = await isTokenExpired(cookieVal);
return cookie;
};
- The isTokenExpired server side utility is basically just a server action / server side function. It parses out the token, as received from the cookieVal variable on the client side, to determine if the token is expired. If it is expired, it forces a logout. However, if it is not expired, it attempts to perform a token refresh to keep the jwt token fresh (generating a new JWT with a new expiration).
export const isTokenExpired = async (token?: string) => {
console.log("in isTokenExpired: ", token);
// Stop execution if no token is provided.
if (!token) return true;
// Decode token and check if it's expired.
const base64Url = token.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
const tokenExpirationDate = new Date(JSON.parse(jsonPayload).exp * 1000);
const now = new Date(Date.now());
const tokenIsExpired = tokenExpirationDate < now;
if (tokenIsExpired) {
// If token is expired, logout() clears the cookies and redirects to login page.
const response = logout();
return response;
} else {
// If token is not expired, refresh it.
const accessToken =
cookies().get("impersonateToken")?.value ??
cookies().get("ssotoken")?.value;
const refreshToken =
cookies().get("impersonateTokenRefresh")?.value ??
cookies().get("ssotokenRefresh")?.value;
if (!accessToken || !refreshToken) return;
// Refresh token if not expired.
const tokenData = await refreshAccessToken(accessToken, refreshToken);
console.log("tokenDataRefreshToken: ", tokenData.refreshToken);
console.log(
"currentRefreshCookie: ",
cookies().get("ssotokenRefresh")?.value
);
return (
cookies().get("impersonateToken")?.value ??
cookies().get("ssotoken")?.value
);
}
};
- The above function is the server side function that takes the token and checks if it is expired. If it is NOT expired, the server side function called refreshAccessToken is called to perform the refresh and set the new JWT token AND new refresh token to the cookies. Here is that function:
export async function refreshAccessToken(token: string, refreshToken: string) {
console.log("calling refreshToken");
console.log("token: ", token);
console.log("refreshToken: ", refreshToken);
console.log(
"currentRefreshTokencookie: ",
cookies().get("ssotokenRefresh")?.value
);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/refresh`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
accessToken: token,
refreshToken: refreshToken,
}),
}
);
const data = await res.json();
if (cookies().get("impersonateToken")) {
cookies().set("impersonateToken", data.accessToken);
cookies().set("impersonateTokenRefresh", data.refreshToken);
} else {
console.log("refreshing ssotoken");
console.log("accessToken: ", data.accessToken);
console.log("refreshToken: ", data.refreshToken);
cookies().set("ssotokenRefresh", data.refreshToken);
console.log(
"currentRefreshTokencookie1: ",
cookies().get("ssotokenRefresh")?.value
);
cookies().set("ssotoken", data.accessToken);
console.log(
"====================COMPLETED SETTING COOKIES!!!===================="
);
}
return data;
}
As you can see, I have lots of log statements to compare function parameters to the actual cookie values. Here is my problem:
When I manually modify the URL and route to my impersonation page (the page where a user can log in as another user – however, loading the page has no side effects, it simply loads in a form), it seems that this client-to-server api call token refresh process is running. It runs once and functions as expected – it calls the refresh route and issues a new JWT and refresh token and then sets each to its appropriate cookie – according to all my log statements.
HOWEVER, it also appears that a duplicate call is coming through immediately after the COMPLETED SETTING COOKIES statement is printed that is calling the isTokenExpired function all over again. The perplexing thing is that if I log the token value from the arguments AND the cookie values in this second call, they are using the OLD cookie values rather than the values I had just finished setting to cookies.
While I have not identified why this second call is happening, the problem is that this second call executes the refresh route with an outdated refresh token, and so the request returns a 401 unauthorized.
I have not identified why this second call is happening, but the primary concern I have is that I do not understand why this call is referencing the OLD cookie values right after the first call had completed the process of setting the cookies to the new values. I was under the impression that cookies().set(‘ssotoken’) would immediately update the cookies stored in the browser, so that with the next reference to cookies().get(), it would have the updated value. Why is this not working?