Search code examples
nuxt.jsserver-side-renderingnuxt3.js

NuxtLink and SSR


I'm trying to use Nuxt JS for a project. I'm interesting to use VueJS with SSR. But there is something I don't understand.

I've these pages :

/pages
  category
    [sub]
      index.vue
  index.vue

/pages/category/index.vue make an API call to get a list of subcategories, and display a link for each of them.

<template>
    <div>
        <h1>Category</h1>
        <ul>
            <li v-for="subcategory in subcategories" :key="subcategory"><NuxtLink :to="'/category/' + subcategory">{{ subcategory }}</NuxtLink></li>
        </ul>
    </div>
</template>
<script setup>

// returns {'subcat1', 'subcat2'}
    const { data: subcategories , error} = await useFetch('https:/myapi.com/subcategories', {

        headers : {Accept: 'application/json'},
        method: 'GET',
    });

</script>

/pages/category/[sub]/index.vue display the name of the category and a link to the parent page "/category"

<template>
    <div>
        <h1>{{ subcategory }}</h1>
        <ul>
            <li><NuxtLink to="/category">Category</NuxtLink></li>
        </ul>
    </div>
</template>
<script setup>
    const route = useRoute();
    const subcategory = route.params.sub;
</script>

When I go to "/category", the API call is made server side, and I see my subcategories. If I click on a subcategory, I go to /category/subcategory. Then if I click on "/category" I return to the parent page but the API call is made client side !

I don't understand why Nuxt make the API call client side. In order to fix that I've replaced all NuxtLink components by "" tags. It works fine because for each click the page is refreshed, the API call is always made server side.

I don't understand why I need to do that to be sure all API calls are made server side.


Solution

  • I think you understand the SSR concept in a wrong way. SSR does not mean that each page you requested will be rendered on a server. Nuxt with SSR is still a SPA (single-page application), but any initial request to the server will be handled by rendering full page and send HTML to the client. Then client does a hydration and further your Nuxt app works as a regular SPA. It means that further navigation to a new page, where a new data should be loaded will trigger regular server API calls from a client.

    If you have a static site you may change your nuxt.config.js to build a static site. Run generate command, which will produce a static site bundle, so all API calls are done during the build time, not in a runtime.