Sveltekit static app deployed to Vercel gives 404 error when reloading sub routes

31 views Asked by At

I built my Sveltekit application using adapter-static.

Everything works fine locally in my development environment, I can reload sub routes and still get the correct page content.

When deploying to Vercel, I can't reload or go to a sub route page without first going to the index page and navigating to it anymore, as I am prompted with a 404 error.

I tried adding a vercel.json file at the root of my project :

{
    "rewrites": [
        {"source": "/(.*)", "destination": "/"}
    ]
}

But this doesn't work as this is for the react router (I think).

1

There are 1 answers

0
Niiju On

I found a way to fix my issue.

Solution 1 : redirect all routes to their .html equivalent

This is needed because Sveltekit generates sub route pages as for example a sub-route.html file, whereas Vercel seems to be looking for a sub-route/index.html file.

Add a vercel.json file located at the root of the project :

{
  "routes": [
    {
      "src": "/(.*)/?$",
      "dest": "/$1.html"
    }
  ]
}

This will redirect :

  • /my-route -> /my-route.html
  • /my/sub-route -> /my/sub-route.html

But this will NOT redirect routes with trailing slashes :

  • /my-route/ -> ERROR 404
  • /my/sub-route/ -> ERROR 404

Solution 2 : trailingSlash = 'always'

I had defined a +layout.ts file at the root of all routes for my static app, and I added this :

export const prerender = true;
export const trailingSlash = 'always'; // Added this

This forces Sveltekit to generate sub route pages as sub-route/index.html files, and adds a trailing slash to every route.