#double requests

3 messages · Page 1 of 1 (latest)

craggy wyvernBOT
#

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

#

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:

  1. 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 $fetch directly in component setup functions Source (https://nuxt.com/docs/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata).

  2. Layout usage: There's a known issue where useAsyncData and useFetch can run requests twice if the page uses a layout Source (https://github.com/nuxt/nuxt/issues/13369).

  3. 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:

  1. Use callOnce utility: Since Nuxt v3.9, you can use the callOnce utility 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('/')
});
  1. Use useAsyncData or useFetch instead 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).
#
  1. 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).

  2. Add a unique key to useFetch: If the issue persists, you can try adding a unique key to your useFetch call to prevent caching issues:

const { data } = await useFetch("/api/signOut", {
  method: "POST",
  body: { idToken },
  key: Date.now().toString()
});

If these solutions don't resolve the issue, you might need to further investigate your specific setup, as the problem could be related to other parts of your application that aren't visible in the provided code snippet.

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