Next.js Discord

Discord Forum

Data fetching in server components with server actions

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
In a Server Component, I know I can directly call an async function to fetch data from the database.

For better maintainability, I want to extract that function into a separate file. My question is: if I add 'use server' at the top of that file, does that function now behave as a Server Action (e.g., gets treated as a POST request, disables parallelization and caching), even though it’s only being called from a Server Component?

In other words:
Is there any difference between calling a function from a file with 'use server' vs without it, when the call is made from a Server Component?
Or are both treated the same since everything stays on the server?

10 Replies

American black bearOP
🤨
@American black bear 🤨
They're farming replies to be able to post in #discussions
American black bearOP
yea I can see that
American black bearOP
so I guess as there is no network request from the client, there si no difference to call a function from a file with 'use server' vs without it from a server component
Yes there’s no point at all to call a Server Action from a Server Component, since both are Server Side and basically what use server does it opening a door back to the server for Client Components.

I believe I’ve heard from one of the Mods that calling a Server Action in a ServerComponent makes it behave like a regular async function.

That said, you should try NOT to use Server Actions for data fetching, not in server components, not in client components.

Here what you can do is a utility function (no use server) that encapsulates the data fetching logic and then call that function inside your Server Component, or your Route Handlers.

If you need to make sure this function gets only ever called on the Server Side, then add the "server only” package at the top of that file exporting your data access functions.
@American black bear any updates?
American black bearOP
So just to confirm, there’s really no difference? It behaves like any regular async function, right? I guess that also means I’m not getting the automatic caching from Next.js if I call the same function in two server components on the same page… unlike if I used fetch, is that correct?
@American black bear So just to confirm, there’s really no difference? It behaves like any regular async function, right? I guess that also means I’m not getting the automatic caching from Next.js if I call the same function in two server components on the same page… unlike if I used fetch, is that correct?
If data comes embedded in the resulting HTML output for the first page load then yes, it’s fetched on the server like a regular function I guess.

Besides that, yes no more automatic caching behavior.
@American black bear solved?