9

I tried doing something like this in my endpoint routes/users.json.ts :

import * as api from '$lib/api'

export async function get({ query, locals }) {

  const response = await this.fetch('static/data/customers.json')

  return {
    status: 200,
    body: {
      data: response
    }
  }
}

my static folder is located in the routes folder.

I got this error:

...
TypeError [ERR_INVALID_URL]: Invalid URL: /static/data/customers.json
    at onParseError (internal/url.js:259:9)
    at new URL (internal/url.js:335:5)
    at new Request (file:///home/nkostic/code/example/node_modules/@sveltejs/kit/dist/install-fetch.js:1239:16)
...

What am I missing ?

The important thing is that it has to be static json files.

nkostic
  • 565
  • 2
  • 7
  • 19

3 Answers3

9

As @evolutionxbox pointed out, you would need an import rather than a fetch in your case. Luckily vite supports direct imports of .json files.

This allows us to simply import the .json at the top of your file and assigning it an alias, like so:

import * as api from '$lib/api'
import yourJSON as api from 'path-to-file/customers.json'

export async function get({ query, locals }) {
   
  return {
    status: 200,
    body: {
      yourJSON
    }
  }

}
Theo テオ
  • 565
  • 3
  • 5
  • I would prefer the fetch solution so my components do not get bigger like with import. But for simple cases such is mine this is exactly what I need. I aslo realised, thanks to Theo from sveltkit discord chat, that https://vitejs.dev/ is where I would look for more details about this functionality. – nkostic Jun 14 '21 at 15:37
3

SvelteKit's static directory outputs to the root of your published folder, so you don't need to include static in your path. Try fetching /data/customers.json instead.

person_v1.32
  • 2,641
  • 1
  • 14
  • 27
  • Tried different variants with fetch and it did not worked. I would prefer this take since it would not made my components larger but rather just serve the static file. For the simple uses cases such as mock api or some other implementations import works just fine. – nkostic Jun 14 '21 at 15:34
3
  1. Place the json file(s) you want to load in ./static
  2. Use the load function inside <script context="module"> to fetch the data.
<script context="module">
  export async function load({ fetch }) {
    const response = await fetch(`../posts.json`); // stored in static folder
    const posts = await response.json();
    return {
      props: {
        posts: posts
      }
    }
  }
</script>  

<script>
  export let posts;
<script>

See detailed tutorial here: https://codesource.io/how-to-fetch-json-in-svelte-example/

Johannes
  • 316
  • 3
  • 4