sveltekitsveltekit-adapter-static

SvelteKit API routes for static deployment and how to resolve "Cannot prerender a +server file with POST, PATCH, PUT, or DELETE"?


I am trying to develop a site with SvelteKit that will be deployed on one.com. Since this will be a static site, i use @sveltejs/adapter-static.

The issue that I am facing is about prerendering the API endpoints with adapter-static.

The code representing the issue is here:

https://stackblitz.com/edit/node-ewi2yl?file=src%2Froutes%2Fapi%2Fupload%2F%2Bserver.js

In routes/api/upload/+server.js, i experimented with the prerender option. But none of my tries worked after deployment.

/* - In DEV mode, runtime error "Error: Cannot prerender endpoints that have mutative methods".
   - Build fails with error "Error: Cannot prerender a +server file with POST, PATCH, PUT, or DELETE (/api/upload)".
*/
export const prerender = true;

/* - In DEV mode, it works.
   - Build does not fail. But after deploying, the endpoint /api/upload is missing - 404 Not Found.
*/
export const prerender = false;

It seems that POST endpoints would not prerender. Although, my endpoint does not mutate the page. The POST is just meant to put data in a SQLite database (not shown in code above - probably not relevant).

There are almost no hits in Google on Error: Cannot prerender a +server file with POST, PATCH, PUT, or DELETE!

Does anyone know how to handle this scenario?


Solution

  • You cannot have a static site with a backend like this. It does not matter whether the backend affects the page, the server does not have one, so it also cannot write to a DB.

    A static site can only contain static HTML, JS & CSS files that are served to the client.

    You either need to deploy to a platform that works with SvelteKit's server endpoints using a different adapter or remove all server endpoints from your site.

    Client-side code can still interact with APIs deployed elsewhere that support it (e.g. REST APIs that allow cross-origin access).