Skip Navigation

Scott Spence

posts tags speaking contact

Fetch data from two or more endpoints in SvelteKit

1 min read
Hey! Thanks for stopping by! Just a word of warning, this post is over 1 year old, . If there's technical information in here it's more than likely out of date.

Real quick example of how I used Promise.all to fetch data from multiple endpoints in SvelteKit.

This uses the server side fetch that is part of SvelteKit and is destructured into the load function.

Note that the code is in the <script context="module"> tag, this means it runs before the page is loaded.

<script context="module">
  export async function load({ fetch }) {
    const [pagesReq, postsReq] = await Promise.all([
      fetch('/pages.json'),
      fetch('/posts.json'),
    ])
    if (pagesReq.ok && postsReq.ok) {
      const { pages } = await pagesReq.json()
      const { posts } = await postsReq.json()
      return {
        props: {
          pages,
          posts,
        },
      }
    }
  }
</script>

Full file looks a little like this example:

<!-- src/routes/index.svelte -->
<script context="module">
  export async function load({ fetch }) {
    const [pagesReq, postsReq] = await Promise.all([
      fetch('/pages.json'),
      fetch('/posts.json'),
    ])
    if (pagesReq.ok && postsReq.ok) {
      const { pages } = await pagesReq.json()
      const { posts } = await postsReq.json()
      return {
        props: {
          pages,
          posts,
        },
      }
    }
  }
</script>

<script>
  import PagesList from '$lib/nav.svelte'
  export let pages, posts
</script>

<PagesList {pages} />

<h1>Welcome to SvelteKit</h1>
<p>
  Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the
  documentation
</p>

{#each posts as { title, slug, excerpt }}
  <a href={`/posts/${slug}`}>
    <p>{title}</p>
    <p>{excerpt}</p>
  </a>
{/each}

That’s it!

Year to date analytics for this post

Views This Year
1k
Jan 1, 2023 - Jun 1, 2023
Visitors This Year
544
Jan 1, 2023 - Jun 1, 2023
Entries This Year
564
Jan 1, 2023 - Jun 1, 2023

Copyright © 2017 - 2023 - All rights reserved Scott Spence