When to use api route and when to use server action to fetch data in Next.js application?
Unanswered
Manik Islam Mahi posted this in #help-forum
When to use api route and when to use server action to fetch data in Next.js application? If my next.js application has api route available to use next.js server in mobile application.
8 Replies
@Manik Islam Mahi When to use api route and when to use server action to fetch data in Next.js application? If my next.js application has api route available to use next.js server in mobile application.
use the api route to fetch data and use the server action to mutate serverside state. However: don't fetch your own endpoints in server components
@B33fb0n3 use the api route to fetch data and use the server action to mutate serverside state. However: don't fetch your own endpoints in server components
Transvaal lion
What if you need to add cache headers to the requests, wouldn't you then have to fetch your own endpoints?
@Transvaal lion What if you need to add cache headers to the requests, wouldn't you then have to fetch your own endpoints?
no, you can wrap your function that calls the data inside a cache or maybe even the database handler uses the
fetch api to retrieve data (like supabase does)Roseate Spoonbill
Personally, I use different approach: use API route for any API that might be called from outside (e.g. revalidate hook, draft mode hook), and server action for anything that isn't available on the outside - it's less coding to have correct type support.
This way, they do represent two different API layers.
@Manik Islam Mahi solved?
If I don't use the api route, can I use my next.js server for my mobile application? Without api route can I fetch data by postman?
@B33fb0n3 @Roseate Spoonbill
@B33fb0n3 @Roseate Spoonbill
Roseate Spoonbill
It is possible technically, but data sent over server actions is encrypted, with the encryption key changing every build. You could implement controlled rotation, that will not invalidate the way action is called from mobile app, but honestly, it may be a bit too much. I wouldn't try this personally in production setup.
I think for those cases route handlers (api endpoints) are much more fitting. Alternatively a webview, which is only usable in limited cases.
I think for those cases route handlers (api endpoints) are much more fitting. Alternatively a webview, which is only usable in limited cases.