useFetch returns null or undefined data
Your Nuxt useFetch isnβt returning data.
Why this happens
useFetch is a Nuxt composable that runs on both server and client during SSR. If the API route doesnβt exist, the response isnβt destructured correctly, or the endpoint is unreachable during server-side rendering, data will be null. External APIs that block server-side requests are a common culprit.
Fix 1: Check the API route exists
// server/api/users.ts must exist
export default defineEventHandler(() => {
return [{ id: 1, name: 'Alice' }];
});
Fix 2: Handle the response correctly
<script setup>
// β Destructuring wrong
const data = await useFetch('/api/users');
// β
Destructure properly
const { data, error, pending } = await useFetch('/api/users');
</script>
<template>
<div v-if="pending">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else>{{ data }}</div>
</template>
Fix 3: Check for SSR issues
// If the API is external, it might not be reachable during SSR
const { data } = await useFetch('/api/users', {
server: false, // Only fetch on client
});
Alternative solution: Use $fetch for non-reactive calls
If you donβt need reactivity, use $fetch directly inside an event handler or onMounted:
onMounted(async () => {
const users = await $fetch('/api/users');
});
Prevention
- Always check
erroralongsidedataβ a failed request silently returnsnullfor data. - Use Nuxt DevTools to inspect SSR payloads and verify your API routes are registered.
Related: Next.js vs Nuxt Β· Vue.js cheat sheet Β· SSR vs SSG vs CSR Β· Next.js 404 Page Not Found Fix