[Vuejs]-What is the technical difference between Vue's native serverPrefetch() and Nuxt's new fetch() hook for server side rendering

-1👍

After playing around for a while. I’m sharing my experience.

Nuxt fetch() vs serverPrefetch()

Both are almost identical under the hood, and the performance are similar. The difference is Nuxt fetch has additional hooks that are useful helpers for UI rendering.

<template>
  <div>
    <p v-if="$fetchState.pending">Loading...</p>
    <p v-else-if="$fetchState.error">Error...</p>
    <ul v-else-if="data.length">
      …
    </ul>
    <p v-else>No data available</p>
  </div>
</template>

Nuxt fetch() vs mounted()

We can also use fetchOnServer: false, which will process only on the client side as an alternative to the vue native mounted lifecycle to take advantage of the $fetchState hooks in UI component.

<script>
  export default {
    data: () => ({
      posts: []
    }),
    async fetch() {
      this.posts = await this.apiCall()
    },
    fetchOnServer: false,
    methods: {
      apiCall() {
        ...
      }
    }
  }
</script>

0👍

Interesting question. If you’re going the Nuxt way, I’ll recommend using fetch() still, because it will be more integrated into Nuxt, hence more flexible (on top of having some nice helpers/cache).

Also, how did you benchmarked this?

the data was rendered to DOM much faster


You need to take into account that Nuxt3 is coming by the end of the year (probably, beta inc soon), so if you use fetch() or alike, you will not need to update your whole codebase because Nuxt will take care of this.
What I mean, is that serverPrefetch will be probably different (native SSR with Vue3) is probably not as polished as Nuxt can offer.

Nuxt is still the best solution for SSR/SSG that the Vue ecosystem can offer.
Of course, you can make your own thing with vanilla Vue but you’ll probably face some difficulties at some point. For ease of mind, I do recommend to try to make this work with fetch().

👤kissu

Leave a comment