How to serve plain json files with sveltekit?

Viewed 5970

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.

3 Answers

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
    }
  }

}
  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/

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.

Related