Learn how to properly fetch data using Next.js app router and explore the differences from the old page router. Also, understand advanced data fetching techniques with bearer tokens.
tech stack
Next.js
App Router
Data Fetching
published date
last edited time
Data fetching is one of the biggest changes in the Next.js app router
When I switched from the Page router to the App router, I got stuck on data fetching for days. There were no tutorials available on how to use the App router properly.
So, I read the Next.js App router docs, made many projects, and learned a lot.
At first, I wondered why Next.js made such a big change because the App router is completely different from the Page router.
But after learning the App router properly, I loved the change because it made many things simple and straightforward.
Let's compare data fetching in the Page router vs App router.
Here, I'm using the JSONPlaceholder API, which doesn't need any authentication. Feel free to try out the code and see the results for yourself.
Page Router
In the Page Router, we used to fetch data using getStaticProps like this:
In the "pages" folder, there's an "index.js" file representing the homepage.
We fetch data using getStaticProps, returning it as props. Then, we pass these props to the Home function, where we use the data.
App router
In the new App Router, we no longer use getStaticProps. Instead, we directly fetch the data as shown here.
You can also see how simple and straightforward it looks. It's very clean. We're not passing props anymore.
Note: As you can see, we used async and await here. This indicates that this is an asynchronous process. It should first wait for the data to be fetched before proceeding further.
You need to use async and await every time you fetch data on any page.
Data Fetching with Bearer Token
In real projects, APIs often require authentication for access. This typically involves including a bearer token in the request headers. Let's see how to fetch data using a bearer token in the App router.
We make a "utils" folder in the main directory or "src". Inside this "utils" folder, we create a file called "api.js". You can choose any name for this file.
We create this separate function so that we can fetch data using a bearer token. This way, we can use the function in any file without repeatedly passing the bearer token every time we fetch data.
Page router
App router
If you only want to use the fetched data on this page, then use this.
Or
You can also create a separate data fetching function outside the page function in the App router.
I've named this function getData, but you can choose any name you prefer like getBlogs, getProducts, etc.
By exporting this function, you can call it from any page and retrieve the data.
Note: As you can see, we did not use fetch here; instead, we are using the fetchDataFromApi function we made earlier and passing the API endpoint.