vue.jsnuxt.jsruntime-errorvuejs3nuxtjs3

nuxt 3 useFetch() returns the error fetch failed()


I have set up the nuxt 3 from the nuxt 3 official documents and used the only useFetch() composable to fetch data in app.vue file but it returns the error Error: fetch failed() when we reload the page.

Please check the error here

Please check my below code of app.vue file

<template>
{{data}}
</template>

<script setup>
  const { data, pending, error, refresh } = useFetch('https://api.nuxtjs.dev/mountains',
  {
    method: "get",
  });

  console.log(data.value);
  if (error.value) {
    console.log(error.value);
  }
</script>

I have tried useFetch and useLazyFetch composable to fetch the data but both returns the same error when we reload the page. I think there is some issue with client side or server side but don't know much about this. Also useFetch() returns result correctly when we visit that page again but it occurring error on initial api call or we hard reload the page.


Solution

  • I figured it out. The problem is we need to add ssr: false in nuxt.config.js. Maybe SSR is true by default if we need to use server-side rendering but if we want the single file application we need to keep ssr: false. The above error is fixed with this.

    nuxt.config.js

    // https://nuxt.com/docs/api/configuration/nuxt-config
    export default defineNuxtConfig({
        ssr: false,
    })