How to fetch data in server-side component

679 views Asked by At

I am using NextJS 13 with the App Router, and Prisma to manage the db. At first I started using Prisma queries directly in server-side components, instead creating another endpoint in the Api and fetching from there, but someone told me that was not the right way, and I should "fetch" from the Api instead. Is there any actual reason to prefer either way over the other?

Nothing I found on the internet talks about that. Whenever people talk about different ways of fetching data, they either compare server-side fetching to client-side fetching, or server-side queries to client-side fetching and never server-side queries to server-side fetching.

By Prisma queries, I mean something like: db.model.findMany(), and by fetch, I mean sending an axios or fetch request to an Api endpoint that does literally the same thing.

2

There are 2 answers

2
MohamedZh On BEST ANSWER

Your way is right. You should run the prisma queries directly in getServerSideProps and there is no need to make an api for them as you're already in the server and this makes an extra unneeded request. As per next.js documentation,

getServerSideProps or API Routes:

It can be tempting to reach for an API Route when you want to fetch data from the server, then call that API route from getServerSideProps. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both getServerSideProps and API Routes running on the server."

so it's better to keep the api routes for external apis, and run your prisma queries directly in getServerSideProps

0
hemanth vasi On

API is needed only in client components, prisma doesn't work in client components.