#Middleware not running when changing the page with Link

1 messages · Page 1 of 1 (latest)

polar oasisBOT
#

Hi @hasty elm. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

This seems to be a known issue with Next.js where the middleware does not run on subsequent visits to previously viewed (cached) pages when navigating via the Link component. The middleware only runs on the first visit. This issue has been reported in several open GitHub issues such as issue #54001 (https://github.com/vercel/next.js/issues/54001), issue #58025 (https://github.com/vercel/next.js/issues/58025), and issue #50592 (https://github.com/vercel/next.js/issues/50592).

Unfortunately, there is no definitive solution provided yet. However, some users have reported that disabling prefetching for the Link component can help, but this only prevents prefetching and does not solve the issue completely.

Here's an example of how to disable prefetching:

<Link href="/your-page" prefetch={false}>
  Your Page
</Link>

Please note that this is a workaround and may not work in all cases. It's recommended to keep an eye on the open issues for any updates or fixes from the Next.js team.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty elm kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty elm
#

@polar oasis Seems like the pages are cached for about 30 seconds when navigation through the Link component. How to remove the cache or lower the seconds ?

polar oasisBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The caching behavior of the Link component in Next.js is indeed designed to cache pages for a certain duration to improve performance. By default, the cache duration is 30 seconds for default prefetching and 5 minutes for full prefetching. This behavior is explained in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching#duration-3).

To modify this behavior, Next.js introduced experimental support for configuring these values in version 14.2.0. You can use the staleTimes configuration in your next.config.js file to set custom cache durations. Here's an example:

module.exports = {
  experimental: {
    staleTimes: {
      '/your-page': 0, // Set the cache duration for '/your-page' to 0 seconds
    },
  },
}

In this example, the page at '/your-page' will not be cached and will always fetch fresh data on navigation. Please note that this feature is experimental and may change in future versions of Next.js. You can read more about it in the Next.js documentation (https://nextjs.org/docs/app/api-reference/next-config-js/staleTimes).

Remember, modifying cache behavior can impact the performance of your application, so it's important to test thoroughly and consider the trade-offs.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty elm kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty elm
#

@polar oasis This config does not work for me for specifick routes, is there something wrong?

polar oasisBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Hmm, I don't know enough to give you a confident answer yet. The staleTimes configuration should work as described in the Next.js documentation (https://nextjs.org/docs/app/api-reference/next-config-js/staleTimes). However, it's possible that there might be a bug or an issue with your specific setup.

Here are a few things you could check:

  1. Make sure you're using a version of Next.js that supports the staleTimes configuration. This feature was introduced in version 14.2.0.

  2. Check your next.config.js file for any syntax errors or misconfigurations. The staleTimes configuration should be inside the experimental object, like this:

module.exports = {
  experimental: {
    staleTimes: {
      '/your-page': 0,
    },
  },
};
  1. Make sure the path you're providing in the staleTimes configuration matches the path of the page you're trying to configure. The path should be a string and should start with a /.

If you're still having issues, it might be helpful to look for similar issues in the Next.js GitHub repository (https://github.com/vercel/next.js/issues) or ask for help in the Next.js community (https://nextjs.org/community).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty elm kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty elm
#

@polar oasis Auth.js how, how to SignOut automatically on token expiration in middleware?

polar oasisBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To automatically sign out a user when their token expires, you can check the token's validity in your middleware. If the token is expired, you can clear the authentication cookies, effectively signing out the user. Here's a simplified example based on the code snippets from the knowledge sources:

export async function middleware(request) {
  // ... other code ...

  // Get the access token from the cookies
  const accessCookie = request.cookies.get('access');

  // Verify the access token (you'll need to implement this function)
  const user = await verifyAccessToken(accessCookie);

  // If the token is invalid (i.e., it's expired or not present), clear the auth cookies
  if (!user) {
    clearAuthCookies(response);
    // Redirect to the login page or handle the sign out in another way
    return NextResponse.redirect('/auth/login');
  }

  // ... other code ...
}

function clearAuthCookies(response) {
  response.cookies.set('auth', 'false');
  response.cookies.set('access', '', {
    httpOnly: true,
    expires: new Date(0),
  });
  response.cookies.set('refresh', '', {
    httpOnly: true,
    expires: new Date(0),
  });
  return response;
}

In this example, verifyAccessToken is a function that checks if the access token is valid. If the token is invalid or expired, the clearAuthCookies function is called to clear the authentication cookies, effectively signing out the user.

Please note that this is a simplified example and you'll need to adapt it to your specific use case. You'll also need to implement the verifyAccessToken function to check the validity of the access token.

For more information, you can refer to the following knowledge sources:

#

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty elm kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty elm
#

@polar oasis I am using middleware to check for token expire date, how to prevent the middleware to continue with the request and also redirect on the login page.

const currentTimestamp = Math.floor(Date.now() / 1000);
if(tokenExpire && token && currentTimestamp >= +tokenExpire) {
const response = NextResponse.json({ message: 'Token has expired' }, { status: 401 });
response.cookies.delete(ECOOKIES.TOKEN);
return response;
}

polar oasisBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In your middleware, you can use NextResponse.redirect() to redirect the user to the login page when the token has expired. Here's how you can modify your code:

const currentTimestamp = Math.floor(Date.now() / 1000);
if(tokenExpire && token && currentTimestamp >= +tokenExpire) {
  // Delete the token cookie
  const response = NextResponse.next();
  response.cookies.delete(ECOOKIES.TOKEN);

  // Redirect to the login page
  return NextResponse.redirect('/login');
}

In this example, /login is the path to your login page. You should replace it with the actual path if it's different in your application.

This will stop the current request and redirect the user to the login page when the token has expired. The NextResponse.redirect() method sends a response with a 307 status code and a Location header pointing to the provided URL, causing the browser to redirect to that URL.

For more information, you can refer to the following knowledge sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@hasty elm kapa.ai is still learning and improving, please let us know how it did by reacting below

hasty elm
#

@polar oasis do cookies have expire time by default?

polar oasisBOT
#

Let me check the knowledge base for you. One moment! :books:

#

No, cookies do not have an expiration time by default. If no expiration time is set, the cookie is considered a "session cookie" and will be deleted when the user closes their browser.

This is explained in the Github Issue (closed): Cookies() does not reflect .set() priority attribute into set-cookie > Original post Part 4 (https://github.com/vercel/next.js/issues/56848) and Vercel > Guides > Understanding Cookies > How Do Cookies Work? Part 1 (https://vercel.com/guides/understanding-cookies) knowledge sources.

Here's an excerpt:

/**
 * Specifies the `Date` object to be the value for the {@link <https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires`> `Set-Cookie` attribute}. By default,
 * no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
 * it on a condition like exiting a web browser application.
 */
expires?: Date | undefined;

You can set an expiration time for a cookie using the expires attribute (which accepts a Date object) or the maxAge attribute (which accepts a number of seconds). If both expires and maxAge are set, maxAge takes precedence.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: