NuxtN
Nuxt13mo ago
kāné

Nuxt 3 API Endpoint Data Lost During Server-Client Transfer Despite Valid Server-Side Data

I'm experiencing a puzzling issue with my Nuxt 3 application where data is being lost during the transfer from server to client, despite the data being valid on the server side.

Setup

I have a view model that handles data transformation:
class ItemViewModel {
  // ... other properties and methods

  toJSON() {
    return {
      id: this.id,
      title: this.title,
      description: this.description,
      // ... other properties
    };
  }
}


And an API endpoint that returns this data:
// server/api/items/[id].get.ts
export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id');
  const result = await MyService.getItem(id);
  const item = ItemViewModel.fromData(result);
  
  // Server-side console shows this data is valid
  console.debug('item.toJSON():', item.toJSON());  // Shows correct data structure
  
  return item.toJSON();
});

On the client side, I'm fetching the data:
<script setup>
const route = useRoute();
const { data, pending, error } = await useFetch(`/api/items/${route.params.id}`);

// data.value is null, despite server logs showing valid data
console.log('Client data:', data.value);  // null
</script>

The Weird Part

  • The server-side logs show the data is valid and structured correctly
  • If I explicitly return a plain object with the same properties within the API endpoint, instead of `return item.toJSON()` it works:```typescript// server/api/items/[id].get.ts...// This worksreturn {id: item.toJSON().id,title: item.toJSON().title,description: item.toJSON().description};```
  • Returning item.toJSON() results in a `null` response on the client side
  • I've tried various serialization approaches (superjson, JSON.stringify/parse) but the issue persists
What's going on here? Why does explicitly creating a new object work while returning the toJSON() result doesn't? Is there something about Nuxt's serialization that I'm missing?
Was this page helpful?