0

My team and I are building a web app with Next.JS, and we are mainly working on Front-end. The back-end was already implemented with another language because it's shared with our mobile apps.

Now I'm struggling with one problem for 3 days. My authentication api will return access_token and refresh_token, and my code store this in cookies. In my middleware, everytime the app routes, I will check whether access token exist in cookies or not and refresh if it expired.

Here is the problem, when the app routes to new page, the access token is expired and the app refresh it in the middleware, new access token will be stored in cookies, but the FE code somehow doesn't get access token in cookies and thus renders as if users logged out. The synchronization of cookies between middleware and front-end has a little bit delay? ChatGPT 4, 3o-mini, Claude, and Cursor recommended me to add some setTimeout for delay but no, I think that's not a good idea.

Do you guys have any idea or best practice for this?

Thank you

I use Next.js 15.2.3, js-cookies 3.0.5

Here is my code

middleware.tsx

...
  const newTokens = await refreshAccessToken(refreshToken);
    
  if (newTokens) {
    // Create response with new access token
    const newAccessToken = newTokens.newAccessToken;
    const newRefreshToken = newTokens.newRefreshToken;
          
    setTokens(newAccessToken, newRefreshToken);
  }
...

front-end code

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const { accessToken } = getTokens();
        setIsAuthenticated(!!accessToken);
      } catch {
        setIsAuthenticated(false);
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, [pathname]);

cookies.ts

  // Set access token with 1 hour expiry
  Cookies.set(TOKEN_COOKIE_NAME, accessToken, { ...cookieOptions, expires: 1/24/}); // 1 hour
  
  // Set refresh token with 7 days expiry
  Cookies.set(REFRESH_TOKEN_COOKIE_NAME, refreshToken, { ...cookieOptions, expires: 7 }); // 7 days
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.