Next JS 14 Server Side Cookies Mismatch

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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật