T
TanStack6mo ago
correct-apricot

API routes vs Server Functions

I'm experimenting with Start in a new project and loving it so far. I'm looking for some guidance on API routes vs Server Functions. When would I choose one vs the other? Especially given the docs indicate that server functions will have configurable URLs in the future I suspect validation may be the answer that seems built-in with functions but maybe not routes?
3 Replies
absent-sapphire
absent-sapphire6mo ago
if you want to expose APIs to the the outside, then use API routes. if you just want to communicate between frontend and backend without exposing, use server functions.
solid-orange
solid-orange3mo ago
Let me make a follow up question, if my server functions are always calling my other backend API (another application - django), should I still use server functions?
rare-sapphire
rare-sapphire3mo ago
There may be another hidden difference. Imagine this scenario, which I have run into with next.js: 1. User visits your site 2. User clicks around on the site, calling API routes (next.js) 3. The next.js server is restarted either from deploying a new version or similar 4. The user is still clicking around on your site, calling API routes Because API routes are stable from the outside, the user won't notice a thing. But if you were to substitute them with server functions, the user would get 500 responses from the server because it can't find a server function with a specific reference that the client tries to call. But if tanstack start doesn't work this way, then the point is moot

Did you find this page helpful?