Skip Navigation

Scott Spence

Fetch data from two or more endpoints in SvelteKit

1 min read

1 person viewing this page live

Read to the end of the post for more stats

Hey! Thanks for stopping by! Just a word of warning, this post is about 2 years 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!

There's a reactions leaderboard you can check out too.

Analytics Information

Daily analytics for this post

Views Today
2
Dec 3, 2023 5:28 AM
Visitors Today
1
Dec 3, 2023 5:28 AM
Entries Today
1
Dec 3, 2023 5:28 AM

Monthly analytics for this post

Views This Month
104
Dec 1, 2023 - Dec 3, 2023
Visitors This Month
66
Dec 1, 2023 - Dec 3, 2023
Entries This Month
61
Dec 1, 2023 - Dec 3, 2023

Yearly analytics for this post

Views This Year
1.9k
Jan 1, 2023 - Dec 3, 2023
Visitors This Year
1.1k
Jan 1, 2023 - Dec 3, 2023
Entries This Year
1.1k
Jan 1, 2023 - Dec 3, 2023

Copyright © 2017 - 2023 - All rights reserved Scott Spence