0
votes

Newbie to Sapper and Svelte, have used other frameworks.

I've created an author site in sapper that lists author's books on the main page, and then a book-specific page linked from the book items - the book page is in books/[slug].svelte (and books/[slug].js for the server side.)

Going to the book page from the link (located in another component) renders perfectly - no issues.

If I reload, or type in the book url directly, there's no html: the page shows the json for the book item. The inspector shows only a pre tag filled with the json.

The site is patterned pretty much after the demo site created from the degit rollup template (and modified from that.)

Any idea what's happening, here? What am I missing, I wonder?

Thoughts appreciated. I can provide more details and a github repo, if needed.

1

1 Answers

2
votes

The issue is that you have overlapping routes -- your API route and your page are both located at /books/slug-goes-here. When you navigate client-side, Sapper swaps in the new Svelte component and does not request anything from the server. When you go there directly, the browser requests /books/slug-goes-here and receives the JSON from your API.

To fix this, you should rename your server route to [slug].json.js and fetch /books/slug-goes-here.json in your component. This way, you have two different routes: /books/slug-goes-here returns the HTML page and /books/slug-goes-here.json returns the JSON data for that page.

<!-- [slug].svelte -->
<script context="module">
    export async function preload({ params }) {
        // this is the component located at books/[slug]
        // it requests books/[slug].json to get its data
        const res = await this.fetch(`books/${params.slug}.json`);
        const data = await res.json();

        // etc
    }
</script>