#double requests
3 messages · Page 1 of 1 (latest)
Based on the information provided in the knowledge sources, there are a few potential reasons why you might be seeing double requests in your Nuxt application:
-
Server-side rendering and hydration: Nuxt's isomorphic nature can sometimes cause data fetching to occur twice - once on the server and once on the client during hydration. This is a common issue when using
$fetchdirectly in component setup functions Source (https://nuxt.com/docs/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata). -
Layout usage: There's a known issue where
useAsyncDataanduseFetchcan run requests twice if the page uses a layout Source (https://github.com/nuxt/nuxt/issues/13369). -
Middleware execution: Your global middleware might be running on both server and client side, potentially causing duplicate requests Source (https://stackoverflow.com/questions/78466983).
To address these issues, you could try the following:
- Use
callOnceutility: Since Nuxt v3.9, you can use thecallOnceutility to ensure your logout logic runs only once Source (https://nuxt.com/docs/api/utils/call-once). Here's how you could modify your code:
await callOnce(async () => {
const auth = getAuth();
const idToken = useCookie("__token");
await signOut(auth);
const { data } = await useFetch("/api/signOut", {
method: "POST",
body: { idToken },
});
await navigateTo('/')
});
- Use
useAsyncDataoruseFetchinstead of$fetch: These composables are designed to handle server-side rendering and hydration properly Source (https://nuxt.com/docs/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata).
-
Check your middleware: Ensure your global middleware isn't running unnecessarily on both server and client. You can use conditions to skip middleware execution in certain scenarios Source (https://stackoverflow.com/questions/78466983).
-
Add a unique key to
useFetch: If the issue persists, you can try adding a unique key to youruseFetchcall to prevent caching issues:
const { data } = await useFetch("/api/signOut", {
method: "POST",
body: { idToken },
key: Date.now().toString()
});