Give API Routes the same love as Form Actions #10907
ebrenner-code
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I see great potential for an improved dev experience, something I struggle with on every svelte project and I don't even think it would be hard to build.
Now that Svelte 5 is nearing release, I am sure that the team is working on the next version of SvelteKit. I have a lot of faith in the team to make decisions and add features that veterans love and improve adoption.
The Svelte team put a lot of work into Form Actions and those features have been received with a lot of enthusiasm.
There are times however when form actions don’t make the most sense and I reach for server endpoints. When you start writing frontend code that needs to access server side endpoints, it feels clunky in comparison to form actions. Svelte isn’t doing anything wrong here to make this process difficult, but it also isn’t doing anything to make it great.
Let me paint the scenario…
You have a button, that when clicked, should fetch a user's latest messages. You need to check the user has credentials for the db (via a secret key), so a server-side trip is necessary. Here’s how that works currently:
client-side fetch() → server.js fetch() → DB
if you want to reuse this function then it looks like:
import/call function() → client-side fetch() → server.js fetch() → DB
Here are the problems with this.
Proposed solution
Allow the import of server-side functions to +page.svelte files. Under the hood, the compiler would simply create an endpoint with the function. It would prevent it from being accessed externally (maybe via Bearer Token). It would create a client side fetch that pass the function arguments as body params. It turns our 3 files into one. Takes our non-public endpoints out of our routes folder and handles much of the boilerplate involved in fetches.
Here’s all that expressed in code.
Existing Method
Proposed Structure
This would compile into the existing method at build time.
I think just comparing the number of lines of code in each example diminishes the problem. The benefit grows with every element of complexity added to these functions. This removes the many directories/sub-directories from the “api” folder. It makes the purpose of these functions more clear as server functions, it means we don’t ned to chase the references to multiple files.
Beta Was this translation helpful? Give feedback.
All reactions