N
Nuxt2mo ago
plex

[Nuxt 3.16] useFetch data empty on SSR

Let's take a basic api fetch:
<script setup>
const {
data: initialData,
status,
refresh,
error,
} = await useFetch("/api/test");

console.log("Data:", initialData.value);

const posts = ref([]);
posts.value = initialData.value ?? [];
</script>

<template>
<div v-if="posts.length > 0">
<div v-for="post in posts" :key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
<script setup>
const {
data: initialData,
status,
refresh,
error,
} = await useFetch("/api/test");

console.log("Data:", initialData.value);

const posts = ref([]);
posts.value = initialData.value ?? [];
</script>

<template>
<div v-if="posts.length > 0">
<div v-for="post in posts" :key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
This works totally fine in dev mode: the data value is populated upon navigating to the page and also on page reload. For some reason, this doesn't work anymore in production - even when I build the project locally. After reload, you can actually see the posts data render for a sec, but then they disappear again and the page is empty. The console.log on the client is also empty. So it seems like the data isn't really passed from the server to the client. This used to work before and it also works in a new project. So there has to be something within my codebase preventing the fetch method from working correctly. I can't share the whole code here, but maybe you could give me a hint where to look?
3 Replies
kapa.ai
kapa.ai2mo ago
Hi @plex. 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 you've provided, it sounds like you're experiencing an issue with useFetch data not persisting after page reload in production. This is a known behavior that can occur in Nuxt applications. Let me suggest some potential causes and solutions. Possible Causes 1. Caching Issues: useFetch caches responses by default, and sometimes this can cause unexpected behavior, especially when moving from development to production. 2. Key Generation: The automatic key generation for useFetch might not be working as expected in your production environment. 3. SSR vs Client Hydration: There might be a mismatch between what's rendered on the server and what's hydrated on the client. Solutions to Try 1. Add a Custom Key Try adding a unique key to your useFetch call to prevent caching issues:
const {
data: initialData,
status,
refresh,
error,
} = await useFetch("/api/test", {
key: 'test-data-' + Date.now()
});
const {
data: initialData,
status,
refresh,
error,
} = await useFetch("/api/test", {
key: 'test-data-' + Date.now()
});
This approach has helped others with similar issues, as mentioned in Stack Overflow. 2. Use useState for Reactive Data Try using useState instead of ref for your reactive data:
const posts = useState('posts', () => []);
posts.value = initialData.value ?? [];
const posts = useState('posts', () => []);
posts.value = initialData.value ?? [];
This ensures the state is properly shared between server and client. 3. Check for Emit Issues If you're using component emits with useFetch, there's a known issue where SSR might be incomplete. This was discussed in a GitHub issue. 4. Replace useFetch with useAsyncData and $fetch Some users have found success by replacing useFetch with a combination of useAsyncData and $fetch:
const { data: initialData } = await useAsyncData('test-data', async () => {
try {
return await $fetch('/api/test')
} catch (error) {
console.error(error)
return null
}
})
const { data: initialData } = await useAsyncData('test-data', async () => {
try {
return await $fetch('/api/test')
} catch (error) {
console.error(error)
return null
}
})
This approach was mentioned as a solution in a Stack Overflow post. 5. Check for Error Responses There was a bug in earlier versions of Nuxt 3 where error responses from useFetch would be cached incorrectly. Make sure you're using the latest version of Nuxt, as this was fixed in Nuxt 3.8.1 according to Stack Overflow. Where to Look in Your Codebase 1. Custom Fetch Wrappers: If you have any custom wrappers around useFetch, check if they're properly handling the response. 2. Middleware or Plugins: Check if any middleware or plugins are interfering with the fetch process. 3. Build Configuration: Review your Nuxt configuration for any settings that might affect data fetching in production. 4. Server Routes: Ensure your API endpoint is correctly set up and accessible in production. If none of these solutions work, you might want to create a minimal reproduction of the issue to help identify the specific cause in your codebase. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@692412885678293578> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
plex
plexOP2mo ago
Okay now that's interesting: if I remove the @nuxt/image module it works again. Vice versa, if I add @nuxt/image to a new project, the data won't load correctly. What could be the reason for this? Update: It's not necessarily @nuxt/image, as I can't always reproduce this, e.g. on Vercel. But rolling back to Nuxt 3.15.4 definitely fixes it, so it has to do with the latest Nuxt version. Anyone with an idea what might be causing this?

Did you find this page helpful?