Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my SvelteKit API work in production (Github Pages)?

Background

I have my project deployed to Github Pages here: https://zeddrix.github.io/jw-guitar-tabs, so I have this in my svelte.config.js file:

kit: {
    ...
    paths: {
        base: '/jw-guitar-tabs'
    },
    appDir: 'internal',
    ...
}

I have this in my __layout.svelte:

<script lang="ts">
    import { base } from '$app/paths';
    ...
    const fetchFromDBAndStore = async (category: SongCategoriesType) => {
        const res = await fetch(`${base}/api/categories/original-songs`);
        const data = await res.json();
        console.log(data);

    ...other code...
    };

    ...I have my code here that uses this data...
</script>

<Layout><slot /></Layout>

Side note: I put it in this file so that this runs on any page, but I have a code to make sure that this doesn't run if I already have the data. This is not the issue.

This calls on the file: src/routes/api/categories/original-songs.ts:

import fetchSongsDB from '$utils/fetchSongsDB';

export const get = async () => fetchSongsDB('originals');

And this fetchSongsDB function fetches the songs from my database.

Everything is working fine in development mode when I run npm run dev and even in preview mode when I run npm run preview after build, of course, in localhost:3000/jw-guitar-tabs.

enter image description here

Issue

However, on the static github page at https://zeddrix.github.io/jw-guitar-tabs, I get this:

enter image description here

enter image description here

It serves the 404 Github Page as the response. I guess it's because it can't find the src/routes/api/categories/original-songs.ts file. But of course Github will not find this file because the deployed folder to gh-pages is the build folder so I don't have this original file route anymore.

enter image description here

How would I solve this?

like image 222
Zedd Avatar asked Nov 16 '25 20:11

Zedd


1 Answers

  1. Rename original-songs.ts to original-songs.json.ts
  2. Change the
fetch(`${base}/api/categories/original-songs`);

to

fetch(`${base}/api/categories/original-songs.json`);

That allows the adapter-static to generate the json files at build time.
(These are static files, to see changes made in mongodb will require a rebuild & redeploy to GitHub pages)

  1. Sometimes the static adapter doesn't autodetect the endpoint.
    You can help the adapter by specifying the url in svelte.config.js
  kit: {
    prerender: {
      entries: [
        "*",
        "/api/categories/original-songs.json",
  1. Bonus tip: The /favorites url redirects to /favorites/ when refreshing the page, add trailingSlash: "never", to kit to generate favorites.html instead of favorites/index.html and keep the /favorites url on refresh.
like image 94
Bob Fanger Avatar answered Nov 18 '25 21:11

Bob Fanger