·
1 min read

Nuxt Tip: Parallel Fetch Requests

Nuxt Tip: Parallel Fetch Requests Image

When you're working with Nuxt, you might find yourself in a situation where you need to fetch multiple pieces of data from different endpoints.

If you fetch the data sequentially, it can slow down the loading time of your application. Fetching the data in parallel can help you load the data faster and improve the performance of your application.

The Problem

Let's say you have two API endpoints that you need to fetch data from and you need to await both requests before rendering the page. Here's how you might do it:

Component.vue
<script setup lang="ts"> const { data: userData } = await useFetch('/api/user'); const { data: bookingData } = await useFetch('/api/booking'); </script>

In this example, Nuxt will fetch the user data first and then the booking data. If the user data takes a long time to load, it will delay the booking data from loading as well.

The Solution

To fetch data in parallel, you can use Promise.all() along with the useAsyncData composable provided by Nuxt:

Component.vue
<script setup lang="ts"> const { data } = await useAsyncData(() => { return Promise.all([ $fetch('/api/user'), $fetch('/api/booking'), ]) }); </script>

By fetching the data in parallel, you can load the user and posts data simultaneously, which can significantly reduce the time it takes to load the page.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.