Sobes.tech
Middle+

How many times will the native fetch execute in an SSR application on Nuxt? How to make a single request? Where will the client get the data from?

sobes.tech AI

Answer from AI

In an SSR application using Nuxt, the native fetch (for example, in the asyncData or fetch hook) is executed on the server by default during page rendering. When navigating on the client (for example, SPA navigation), fetch may be executed again if special mechanisms are not used.

To make a single request and avoid re-calling fetch on the client, you should use Nuxt's built-in data caching capabilities. For example, data obtained on the server is automatically injected into the HTML and accessible on the client via window.__NUXT__. This allows the client to retrieve data from the server-generated state instead of making a repeated request.

Example:

export default {
  async asyncData({ $axios }) {
    const data = await $axios.$get('/api/data')
    return { data }
  }
}

Here, the request is executed on the server during the initial render, and the client receives the data from the embedded state without making a repeated fetch.

If fetch is called in hooks that run on both client and server (for example, fetch in Nuxt 2), you can use the process.server or process.client flags to control where to perform the request. Nuxt 3 offers more advanced mechanisms for request separation and caching.

In summary:

  • The request is made once on the server during SSR.
  • Data is serialized and passed to the client in HTML.
  • The client uses this data from the state without making a repeated request.

This helps optimize loading and avoid unnecessary requests.

How many times will the native fetch execute in an… - sobes.tech