Introduction
There are two different ways on how to fetch data. The clientside approach uses an API which makes data fetching a bit more complicated. On the other side is the serverside approach, which is more convenient since its less code to write and generally just more intuitive.
| Overview |
|---|
| Serverside |
| Clientside |
Serverside
Serverside is the approach I previously covered in π Query Database. The code is very minimalistic and straight forward and should be used whenever possible. The main benefits of serverside data fetching are:
- Simpler code and no api route required
- Better security due to no exposure to clientside
- Better SEO because search engines get to see the whole data
- Fewer network traffic and waterfalls
Here is a simple example of how a serverside data fetch could look like:
| More on serverside data fetching |
|---|
| π Query Database |
Clientside
In order to get clientside data fetching, I do need to create an API. I can do so with creating the /src/api folder. Just like the app folder, the api will also create automatically the routes for me when following the naming convention. While itβs recommended to use serverside data fetching, there are still a few benefits of clientside data fetching:
- Interaction with other systems
- Content updates frequently and depends on user input
| More on clientside data fetching |
|---|
| Next.js Docs > API Routes |
Conclusion
Itβs good to know that there are both ways on how to fetch data. However I definitely will try to implement whenever possible the serverside approach, because my goal will always be to give as less data as needed to the clientside. But I do know I will arrive at the point where there is no other way than using clientside data fetching - and tbh Iβm still looking forward to create an api.