Search code examples
server-side-renderingnuxt3.js

when and how an ssr app should fetch data


i'm very new to nuxt and ssr in general and i'm confused about how ssr works

if i understand correctly the server will render only the initial page then if the user navigate to another pages the app will behave like a spa.

my question is say i have 2 pages in the website

1-- orders 2--Clients

if a user visit for the first time the website he we get the orders page (default page) so the page will be rendered in the server side.

but if he navigate to the clients page, the page should be rendered in the client side

what hook exactly should i use to fetch data and if data is fetched in the server side how i can tell the client side that the server has already fetch the data and there is no need to fetched again


Solution

  • The thing is, you are not getting fetched data from a server. You're getting an HTML file which contains fetched data pasted/rendered in an HTML file on server side. So you're getting data fetch twice if you're not using any hook. Hooks works only on SPA, so they are triggered on client side only.

    This will be fetched and rendered twice on initial/first page load.

    <template>
      <p>{{ data }}</p>
    </template>
    
    <script setup>
    const { data } = await useFetch(...)
    </script>
    

    This will be fetched only on client side rendered twice but with no fetched data:

    <template>
      <p>{{ data }}</p>
    </template>
    
    <script setup>
    const data = ref('')
    onMounted(async () => {
      const result = await useFetch(...)
      data.value = result.data
    })
    </script>
    

    Component inside <ClientOnly> tag won't be rendered on server side.

    <template>
      <ClientOnly>
         <Login></Login>
      </ClientOnly>
    </template>
    

    Oh, and if you're not make or use some special libraries which will check are you already have data you want to fetch, you still fetch data every time you change a route.